Java 8 stream – merge two sets to make them unique in a specific field [copy]
•
Java
See English answers > java 8 distinct by property 20
This is the best I can do in Java, but it collects unique names instead of dogs: (dogs contain fields other than names)
// collect all dogs names from first list List<String> dogNames1 = dogsList1.stream() .map(x -> x.getName()).collect(Collectors.toList()); dogList2.stream() .filter(x->!dogNames1.contains(x.getName())) .forEach( x-> dogsList1.add(x); );
Can it be improved? There are other better solutions or optimization methods
Solution
You can use to merge multiple streams and delete duplicates
For the first dog with a given name, you can do it
import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class A { public static void main(String[] args) { List<Dog> dogList1 = Arrays.asList(new Dog("a",1),new Dog("b",2),new Dog("f",3)); List<Dog> dogList2 = Arrays.asList(new Dog("b",4),new Dog("c",5),6)); List<Dog> dogList3 = Arrays.asList(new Dog("b",7),new Dog("d",8),new Dog("e",9)); List<Dog> dogs = new ArrayList<>( Stream.of(dogList1,dogList2,dogList3) .flatMap(List::stream) .collect(Collectors.toMap(Dog::getName,d -> d,(Dog x,Dog y) -> x == null ? y : x)) .values()); dogs.forEach(System.out::println); } } class Dog { String name; int id; public Dog(String name,int id) { this.name = name; this.id = id; } public String getName() { return name; } @Override public String toString() { return "Dog{" + "name='" + name + '\'' + ",id=" + id + '}'; } }
Dog{name='a',id=1} Dog{name='b',id=2} Dog{name='c',id=5} Dog{name='d',id=8} Dog{name='e',id=9} Dog{name='f',id=3}
In each case, you can see the first instance of the reserved name
For unique names
Set<String> names = Stream.of(dogList1,dogList3) .flatMap(List::stream) .map(Dog::getName) .collect(Collectors.toSet());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码