Java streams filter OR condition

Viewed 34

I have this list of string values. My condition is to filter out NON numeric values that are not of length 6. I got the 2 filters below,how do i add in my or condition?

Thanks

List<String> teList = new ArrayList<String>();
teList.add("123456");
teList.add("76543W");
teList.add("123R56");
teList.add("888888");
teList.add("7652");
teList.add("222222222222");
teList.add("1234526R");
teList.add("76543222R");

List<String> exlist = teList.stream()
    .filter(s -> !s.matches("[0-9]+"))
    .filter(s -> s.length() != 6)
    .collect(Collectors.toList());
    System.out.println(exlist.toString());
1 Answers

Invert your conditions and join them with an or (||). (You want to keep values that are numeric or have a length of 6. See De Morgan's laws.)

List<String> exlist = teList.stream()
    .filter(s -> s.length() == 6 || s.matches("[0-9]+"))
    .collect(Collectors.toList());
Related