I am learning many new features of lambda and wondering how can I group by my custom object list based on certain properties as key?
For example, I have list of object like this in json.
[{
"account" : "checking",
"source" : "BOA"
},
{
"account" : "checking",
"source" : "TD"
},
{
"account" : "saving",
"source" : "WS"
}
]
I am looking for way to group using java 8 feature to get output like this (grouping source as comma separated for same account.
[{
"account" : "checking",
"source" : "BOA, TD"
},
{
"account" : "saving",
"source" : "WS"
}
]
Thanks
解决方案
What about this solution
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Data {
public static void main(String ab[]) {
List dataList = Arrays.asList(new Data("checking", "BOA"), new Data("checking", "TD")
, new Data("saving", "WS"));
List newList = new ArrayList<>(dataList.stream()
.collect(Collectors.toMap(Data::getAccount, d -> d, (d1, d2) -> new Data(d1.account, d1.source + ", " + d2.source)))
.values());
System.out.println("dataList = " + dataList);
System.out.println("newList = " + newList);
}
private String account;
private String source;
Data(String account, String source) {
this.account = account;
this.source = source;
}
@Override
public String toString() {//just override toString as json object with out using jon passer
return "{ \"account\" : \""+account+"\", \"source\" : \""+source+"\" }";
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
}