Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access all elements after stream filter

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?

like image 206
Volodimir Shmigel Avatar asked Jan 13 '18 17:01

Volodimir Shmigel


People also ask

How do I get one element from a stream list?

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.

Does stream filter modify the original list?

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.

What does stream filter () operates on?

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.


2 Answers

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]
like image 192
Bernhard Barker Avatar answered Oct 15 '22 12:10

Bernhard Barker


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]
like image 37
sanit Avatar answered Oct 15 '22 11:10

sanit