How to use concat to get different object lists in Java 8
•
Java
I have two Java classes
class A { String name; List<B> numbers; } class B { Integer number; }
I want to get the uniqueness of class A and connect the list of B
For example, suppose I have a list containing the following objects
List<A>{ name = "abc" List<B>{1,2} name= "xyz" List<B>{3,4} name = "abc" List<B>{3,5} }
The result should be:
List<A>{ name = "abc" List<B>{1,2,3,5} name="xyz" List<B>{3,4} }
Any help will be greatly appreciated
Note: I want to use Java 8 streams to achieve this
thank you
Solution
You can use the tomap collector:
Collection<A> result = list.stream() .collect(Collectors.toMap(a -> a.name,a -> a,(a,b) -> {a.numbers.addAll(b.numbers); return a;})) .values();
You can copy the results to the list (such as the new ArrayList < > (results)), but since we do not keep any specific order, using the list is not very useful In most cases, the collection results are good
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
二维码