Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 filtering a string

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();
}
like image 522
Java Programmer Avatar asked Jan 16 '20 14:01

Java Programmer


People also ask

How do I filter a string in Java 8?

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.

How do I filter a list based on another list in Java 8?

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.

How do you filter data in Java?

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.

How do you remove a character from a string in Java?

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).


2 Answers

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 chars), so I wouldn't have to use an IntStream.

like image 93
Eran Avatar answered Oct 13 '22 08:10

Eran


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.

like image 45
Donald Raab Avatar answered Oct 13 '22 10:10

Donald Raab