I have a method to remove some characters from a string. Is there a better way to do this using java 8?
public String filter(String test) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < test.length(); i++) {
if (MYCOLLECTION.contains(test.charAt(i))) {
builder .append(test.charAt(i));
}
}
return builder .toString();
}
Using Java 8 In Java 8 and above, use chars() or codePoints() method of String class to get an IntStream of char values from the given sequence. Then call the filter() method of Stream for restricting the char values to match the given predicate.
After populating both the lists, we simply pass a Stream of Employee objects to the Stream of Department objects. Next, to filter records based on our two conditions, we're using the anyMatch predicate, inside which we have combined all the given conditions. Finally, we collect the result into filteredList.
The filter() function of the Java stream allows you to narrow down the stream's items based on a criterion. If you only want items that are even on your list, you can use the filter method to do this. This method accepts a predicate as an input and returns a list of elements that are the results of that predicate.
The deleteCharAt() method accepts a parameter as an index of the character you want to remove. Remove last character of a string using sb. deleteCharAt(str. length() – 1).
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
.
If you're open to using a third-party library, the following will work using Java 8 with Eclipse Collections.
CharSet set = CharSets.immutable.with('a', 'b', 'c');
CharAdapter chars = Strings.asChars("a1b2c3");
String string = chars.select(set::contains).toString();
Assert.assertEquals("abc", string);
Eclipse Collections has support for primitive collections so there is no need to box char
values as Character
instances.
You can also exclude instead of include characters using the method named reject
which is the opposite of select
.
CharSet set = CharSets.immutable.with('a', 'b', 'c');
CharAdapter chars = Strings.asChars("a1b2c3");
String include = chars.select(set::contains).toString();
String exclude = chars.reject(set::contains).toString();
Assert.assertEquals("abc", include);
Assert.assertEquals("123", exclude);
Note: I am a committer for Eclipse Collections.
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