java 集合运算_java stream 集合运算

1.对列表进行分组,构建成一个map对象。

键为用户名称,值为用户对象列表。

Person p1 = new Person("张三", new BigDecimal("10.0"));

Person p2= new Person("王五", new BigDecimal("10.0"));

Person p3= new Person("李四", new BigDecimal("10.0"));

Person p4= new Person("李四", new BigDecimal("10.0"));

Person p5= new Person("张三", new BigDecimal("10.0"));

List list = new ArrayList<>();

list.add(p1);

list.add(p2);

list.add(p3);

list.add(p4);

list.add(p5);

这个我们之前写代码可以需要写成如下的方式:

private Map> convertToMap(Listlist){

Map> map=new HashMap<>();for(Person p: list){

String name=p.getName();if(map.containsKey(name){

map.get(name).add(p);

}else{

List list=newArrayList();

list.add(p);

map.put(name,p);

}

}returnmap;

}

写了一大段代码。

使用steam 就简单了,一行代码解决问题。

Map> collect = list.stream().collect(Collectors.groupingBy(person ->person.getName()));

System.out.println(collect);

2.将list 转成 map 对象。

Person p1 = new Person("1","张三", new BigDecimal("10.0"));

Person p2= new Person("2","王五", new BigDecimal("10.0"));

Person p3= new Person("3","李四", new BigDecimal("10.0"));

Person p4= new Person("4","李四", new BigDecimal("10.0"));

Person p5= new Person("5","张三", new BigDecimal("10.0"));

List list = new ArrayList<>();

list.add(p1);

list.add(p2);

list.add(p3);

list.add(p4);

list.add(p5);

上面的数据 我们转成 Map 对象。

Map nodeMap = bpmSolUsergroups.stream().collect(Collectors.toMap(p->p.getId(), p -> p));

3.对列表进行过滤

public static voidmain(String[] args) {

List filesInst =new ArrayList<>();

BpmCheckFile file1=newBpmCheckFile();

file1.setJumpId("1");

BpmCheckFile file11=newBpmCheckFile();

file11.setJumpId("1");

BpmCheckFile file2=newBpmCheckFile();

file2.setJumpId("2");

filesInst.add(file1);

filesInst.add(file11);

filesInst.add(file2);

List files= filesInst.stream().filter(p->p.getJumpId()=="1").collect(Collectors.toList());

System.err.println(files.size());

}

对列表数据进行过滤。

4.将JSONARRAY 转换成 Map对象

public static voidmain(String[] args) {

String str="[{id:1,name:'ray'},{id:2,name:'zyg'}]";

JSONArray ary=JSONArray.parseArray(str);

Map map= ary.stream().collect(Collectors.toMap(i->{JSONObject json=(JSONObject)i;return json.getString("id");} , p->{JSONObject json=(JSONObject)p;returnjson;}));

System.err.println(map);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值