Reputation: 253
I am trying to convert a List of Object to another list fo Object. But i am trying to chose the best way using with or without streams by java8 way with more readability.
Lets say i have a list like below:
List<SomeObject> list = new ArrayList<SomeObject>;
SomeObject:
public class SomeObject{
private String var1;
private String var2;
private String var3;
private String var4;
//getters and setters
}
AnotherObject:
public class AnotherObject{
private String var1;
private List<String> var2;
//getters and setters
}
But in the another object if the var1 is same for multiple Objects i want to save the var2 value in a list of String .Example below:
SomeObject so = new SomeObject();
so.setVar1("key1");
so.setVar2("value1");
SomeObject so1 = new SomeObject();
so1.setVar1("key2");
so1.setVar2("value2");
SomeObject so2 = new SomeObject();
so2.setVar1("key2");
so2.setVar2("value3");
list.add(so);
list.add(so1);
list.add(so2);
Now from the above List i want to create List of AnotherObject which has just var1 and var2 and if var1 is same in two SoemObject then i want the var2 values in the list and save it for var1.
Any suggestions are appreciated and helpful.
Upvotes: 3
Views: 104
Reputation: 31868
You seem to be looking for groupingBy
based on var1
and then mapping
to var2
as a list of values. This could be done as:
List<AnotherObject> anotherList = list.stream()
.collect(Collectors.groupingBy(
SomeObject::getVar1, Collectors.mapping(
SomeObject::getVar2, Collectors.toList())))
.entrySet().stream()
.map(e -> new AnotherObject(e.getKey(), e.getValue()))
.collect(Collectors.toList());
Upvotes: 2