Use the Java 8 streaming API to convert a List to Map>… here is a solution to the problem.
Use the Java 8 streaming API to convert a List to Map>
I have the following code:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test {
/**
* @param args
*/
public static void main(String[] args)
{
Test t=new Test();
t.test();
}
class A
{
int id;
B b;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
}
class B
{
int id;
String unique;
public String getUnique() {
return unique;
}
public void setUnique(String unique) {
this.unique = unique;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public void test()
{
B b1=new B();
b1.setId(9999);
b1.setUnique("123456789");
B b2=new B();
b2.setId(7777);
b1.setUnique("123456789");
B b3=new B();
b3.setId(8888);
b3.setUnique("987654321");
A a1=new A();
a1.setId(1);;
a1.setB(b1);
A a2=new A();
a2.setId(2);;
a2.setB(b1);
A a3=new A();
a3.setId(3);;
a3.setB(b2);
A a4=new A();
a4.setId(4);;
a4.setB(b2);
A a5=new A();
a5.setId(5);;
a5.setB(b3);
A a6=new A();
a6.setId(6);;
a6.setB(b3);
List<A> list=new ArrayList<A>();
list.add(a1);
list.add(a2);
list.add(a3);
list.add(a4);
list.add(a5);
list.add(a6);
Map<B,List<A>> map=list.stream()
.collect(Collectors.groupingBy(A::getB));
required output
Map<String, List<A>>
}
}
In this example, I have a class A
, which references class B
. Class B has a field called unique
. As a source, I got a list (a1 to a6) that references Class B objects (b1, b2, and b3). Objects b1 and b2 contain the same unique values. I want to use the output of the Java 8 Stream API, which will return the Map> so that if the unique value of object B referenced by A is the same, then the resulting list should contain a merge of class A objects in the list. For example, the following should be the output
Map<String,List<A>> output = [
"123456789" : [a1,a2,a3,a4],
"987654321" : [a5,a6]
]
Solution
Fixed this line (it’s b1
, but it should have been b2
):
b2.setUnique("123456789");
The correct mapping code looks like this:
Map<String,List<A>> map=list.stream()
.collect(Collectors.groupingBy(p -> p.getB().unique));
The output (A is represented by {ID}
) looks like this:
{123456789=[{1}, {2}, {3}, {4}], 987654321=[{5}, {6}]}