How to replace only the first element of a List<Character> using java streams without making any changes to the rest of the list?

t T s :

I am getting a List and I want to replace the first value in this list with '$' sign, So that I could use it in some place else. But i don't want the rest of the characters in the list to be misplaced or changed. It's okay to get the result as a new list.

I already tried to just use the list.add(index, value) function but it changes the order of the list. But I don't want any change to the rest of the list.

Is there any good tutorials to to learn java streams. I find it confusing to master. Thanks in advance.

If the input list is ('H','E','L','L','O') the output should be exactly like ('$','E','L','L','O').

Ravindra Ranwala :

You can access the list using indices. If the index is zero just map it to a $, otherwise just send it to the next step of the stream processing pipeline. Finally collect it into a List. This approach is better than modifying your source container if you are using Java8. Here's how it looks.

List<Character> updatedList = IntStream.range(0, chars.size())
    .mapToObj(i -> i == 0 ? '$' : chars.get(i))
    .collect(Collectors.toList());

This problem does not lend itself nicely to be solved using Java8 streams. One drawback here is that it runs in linear time and looks we have over engineered it using java8. On the contrary, if you modify your array or list directly chars[0] = '$';, then you can merely do it in constant time. Moreover, the imperative approach is much more compact, readable and obviously has less visual clutter. I just posted the Java8 way of doing it, since you have explicitly asked for that. But for this particular instance, imperative way is far more better in my opinion. Either use an array and set the 0th index or if you need to go ahead with a List for some reason, then consider using List.set instead, as stated in the comments above.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=163831&siteId=1