My task is to filter an array, change the remaining elements and return the array with both the changed and unchanged values. My code:
return Arrays.stream(sentence.split(" "))
.filter(/* do some filter to each value */)
.map(/* map this value*/)
.collect(Collectors.joining());
How can I return an array of the changed and unchanged values?
Using Stream findFirst() Method: The findFirst() method will returns the first element of the stream or an empty if the stream is empty. Approach: Get the stream of elements in which the first element is to be returned. To get the first element, you can directly use the findFirst() method.
That means list. stream(). filter(i -> i >= 3); does not change original list. All stream operations are non-interfering (none of them modify the data source), as long as the parameters that you give to them are non-interfering too.
Stream filter() Method filter() is a intermediate Stream operation. It returns a Stream consisting of the elements of the given stream that match the given predicate. The filter() argument should be stateless predicate which is applied to each element in the stream to determine if it should be included or not.
filter
removes elements. If you don't want to remove elements, but rather just change some of them, you can use ?:
or if-else inside map
to selectively change elements.
For example:
System.out.println(Stream.of("abc", "def", "ghi")
.map(a -> a.equals("def") ? "xyz" : a)
.collect(Collectors.toList()));
Or:
System.out.println(Stream.of("abc", "def", "ghi")
.map(a -> {
if (a.equals("def"))
return "xyz";
else
return a;
})
.collect(Collectors.toList()));
This will only change the element which equals def
to xyz
(for each other element, it will simply keep that element as is) and the output will be:
[abc, xyz, ghi]
We can achieve this without stream also.
List<String> list = Arrays.asList("abc", "def", "ghi");
list.replaceAll(s -> s.equals("def") ? "xyz" : s);
System.out.println(list);
Output
[abc, xyz, ghi]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With