本文介绍了使用Java 8按属性对自定义对象列表进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习lambda的许多新功能,并且想知道如何基于某些属性作为键将自定义对象列表分组?例如,我在json中有这样的对象列表.
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.
我正在寻找使用Java 8功能进行分组以获取这样的输出的方式(将源分组为逗号分隔的同一帐户.
I am looking for way to group using java 8 feature to get output like this (grouping source as comma separated for same account.
谢谢
推荐答案
该解决方案如何
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<Data> dataList = Arrays.asList(new Data("checking", "BOA"), new Data("checking", "TD")
, new Data("saving", "WS"));
List<Data> 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;
}
}
这篇关于使用Java 8按属性对自定义对象列表进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!