java1.8 stream 技巧,java8 JDK1.8 stream 对数据分组操做

以前想对数据进行分组统计之类的操做,须要使用关系型数据库的group by等操做来实现。但这两天工做中碰到一个问题,数据从其余系统获取而再也不是我从数据库中取了,也就是说我无法使用关系型数据库提供的操做方法了。了解了一下java8中stream 对数据的处理。java

此次碰到的需求是,拿到经过dubbo接口调用其余系统返回的数据,而后对这些进行一个相似于聚合的操做,把多个属性相同的对象视为同一个对象。数据库

假设有一个车辆类型this

@Data

public class Car {

private String name;

private int id;

private String color;

public Car(String name, int id, String color) {

this.name = name;

this.id = id;

this.color = color;

}

//constructors, getter/setters

}

List cars = Arrays.asList(

new Car("golf", 1, "red"),

new Car("bmw", 2, "red"),

new Car("mini", 3, "black"),

new Car("ds", 4, "white"),

new Car("bmw", 5, "gold"),

new Car("golf", 6, "red"),

new Car("bmw", 7, "gold"),

new Car("ds", 8,"white")

);

若是想根据名称来分类,而且统计各品牌数量code

Map sum = cars.stream().collect(

Collectors.groupingBy(Car::getName, Collectors.counting()));

System.out.println(sum);

输出结果是:{golf=2, mini=1, bmw=3, ds=2}对象

若是想根据多个字段来分类,能够再另外建立一个封装类型,把要分类的字段放进去,Car类再添加一个方法来获取这个类的对象。接口

@Data

public class Count {

private String name;

private String color;

public Count(String name, String color) {

this.name = name;

this.color = color;

}

}

修改一下Car类get

@Data

public class Car {

private String name;

private int id;

private String color;

public Car(String name, int id, String color) {

this.name = name;

this.id = id;

this.color = color;

}

public Count getCount() {

return new Count(name, color);

}

//constructors, getter/setters

}

Map counting = cars.stream().collect(

Collectors.groupingBy(Car::getCount, Collectors.counting()));

System.out.println(counting);

输出结果:{Count(name=bmw, color=gold)=2, Count(name=mini, color=black)=1, Count(name=ds, color=white)=2, Count(name=bmw, color=red)=1, Count(name=golf, color=red)=2}it

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值