'How to all elements based on property that dont exist on another list
I have two SETs fooSet and barSet of different objects foo and bar with properties:
Class Foo { String name, Integer age }
Class Bar { String name }
I want to know ALL THE ELEMENTS of the fooSet where name does not exist in the barSet
I did multiple things but dont work. I don't know how to fix this issue
barSet.forEach(b -> fooSet.stream().anyMatch(f -> f.getName().equals(b.getName())));
Example:
[Foo: "Johnny", 28; Foo: "Travolta", 10; Foo: "Smith", 15]
[Bar: "Travolta"; Bar: "Smith"]
I want to get Johnny
Any help?
Solution 1:[1]
Those one-liners in the other answers are probably doing their job, but they are not necessarily readable. You could also instead do the following.
First, create a Set with all names of Bar, and then process all Foo objects:
Set<String> names = barSet.stream()
.map(Bar::name)
.collect(Collections.toSet());
Set<Foo> result = fooSet.stream()
.filter(foo -> !names.contains(foo.name()))
.collect(Collectors.toSet());
Solution 2:[2]
You want to search for each entry through the barSet and look if any entry matches the name from the Foo-Object or rather you want to remove the entry from the set when there is no entry in the barSet with the same name:
String name = "Johnny";
Set<Foo> foos = new HashSet<>( Arrays.asList( new Foo( name, 28 ), new Foo("Smith", 20 ) ) );
Set<Bar> bars = Collections.singleton( new Bar( name ) );
foos.removeIf( foo -> bars.stream().noneMatch( bar -> bar.getName().equalsIgnoreCase( foo.getName() ) ) );
Solution 3:[3]
You could filter the fooSet by removing all name that are not present in barSet :
fooSet.stream().filter(foo -> !barSet.stream().map(Bar::getName).collect(Collectors.toList()).contains(foo.getName())).collect(Collectors.toList());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MC Emperor |
| Solution 2 | L.Spillner |
| Solution 3 |
