Skip to content
Advertisement

How to use stream to filter objects from HashSet that have empty value for certain fields?

I am looking for a way to filter only the Worker objects with a specific first name and empty lastName from the given HashSet. For example I want the code to return the record with firstName == scott and lastName == "".

public static void main(String[] args) {
    Worker w1 = new Worker("scott","tiger");
    Worker w2 = new Worker("panthera","tigris");
    Worker w3 = new Worker("scott","");
    Worker w4 = new Worker("alpha","romeo");
    Worker w5 = new Worker("apple","orange");
    Set<Worker> wset = new HashSet<>();
    wset.add(w1);
    wset.add(w2);
    wset.add(w3);
    wset.add(w4);
    wset.add(w5);
    System.out.println(wset.stream().filter(worker -> worker.firstName == "scott" && --something on these lines??--)); // ???
}

Advertisement

Answer

filter is a non-terminal operation and the stream would be processed only when a terminal operation is encountered. More details

So you may use collect to display the filtered elements. Also use equals to compare strings instead of ==. Refer

wset.stream()
    .filter(worker -> worker.firstName.equals("scott") 
                      && worker.lastName.isBlank()); // use isEmpty() instead of isBlank if java version is below 11.
    .collect(Collectors.toList());
}

If you want to do “null safety before I call ” .stream() ” on the collection object” then you could use Stream.ofNullable (since java 9)

Stream.ofNullable(wset)
      .flatMap(Collection::stream)
      // rest of the code from above snippet
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement