Java 8 filtering a string
How about this:
Set<Character> filter = new HashSet<>(Arrays.asList('a','b','c'));
String filtered = "abcdefga".chars ()
.filter(i -> filter.contains((char) i))
.mapToObj(i -> "" + (char) i)
.collect(Collectors.joining());
System.out.println (filtered);
Output:
abca
Note: filter
serves the same purpose as your MYCOLLECTION
- I just gave it a more meaningful name and used a Set
for better performance of contains
.
It could have been cleaner if there was a CharStream
(i.e. stream of primitive char
s), so I wouldn't have to use an IntStream
.