Access to all items after stream filter

My task is to filter the array, change the remaining elements and return the array with changed and unchanged values. My code is:

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 changed values and without changes?

+6
source share
3 answers

filterremoves items. If you do not want to delete elements, but simply change some of them, you can use ?:or if-else inside mapto selectively change the 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()));

, def - xyz ( ), :

[abc, xyz, ghi]
+8

.

List<String> list = Arrays.asList("abc", "def", "ghi");
list.replaceAll(s -> s.equals("def") ? "xyz" : s);
System.out.println(list);

[abc, xyz, ghi]
+3

The easiest option is to use an intermediate operation mapalong with the ternary operator, as mentioned by Dukeling, but another option:

 String result = 
          Pattern.compile(" ")
                 .splitAsStream(sentence)
                 .map(s -> criteria ? modification : s) // partly pseudocode
                 .collect(Collectors.joining(" "));
+2
source

All Articles