2

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??--)); // ???
}
Gautham M
  • 4,816
  • 3
  • 15
  • 37
Andulos
  • 433
  • 6
  • 20
  • 1
    ....`&& worker.lastName.isEmpty()` and you need a terminal operation also after filtering eg: `.collect(Collectors.toSet())` or `.findFirst()` to get first item. – Eklavya Jul 23 '21 at 04:46
  • Also, how can I include null safety before I call " .stream() " on the collection object? – Andulos Jul 23 '21 at 04:55
  • You don't need to filter before `.stream()` you can filter after `.stream()` same way for null items in set. – Eklavya Jul 23 '21 at 04:57

1 Answers1

2

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
Gautham M
  • 4,816
  • 3
  • 15
  • 37