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?
CodePudding user response:
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() ) ) );
CodePudding user response:
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());
CodePudding user response:
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 name
s 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());