Stream-Collectors实例集锦

318 阅读2分钟

这是我参与8月更文挑战的第3天,活动详情查看:8月更文挑战

前言

首先了解一下Collectors是个什么东西,它可以帮助我们完成什么事情。Collectors可以看作sql使用,实现排序、分组、最大最小值、平均求和等功能,完成数据上的一些聚合操作。也可以和List互相转换,满足多元化的编程需求,通过遍历、循环等方法,实现较复杂的业务逻辑,话不多说,直接上实例。

实例一

集合的排序、分组、最大值、最小值、平均值等等。

Collectors.groupingBy(),分组

List<Users> users;
users.stream().collect(Collectors.groupingBy(Users::getAge))

Collectors.maxBy(),取最大值

users.stream().collect( Collectors.maxBy(Comparator.comparing(Users::getId)))

sorted(),排序

倒排
users.stream().sorted(Comparator.comparing(Users::getId).reversed()).collect(Collectors.toList())

实例二

集合的转换、过滤、重组等。

Collectors.toMap(),list转为map

//List转Map
​

List<Item> itemList=new ArrayList();
​
//第一种写法
Map<Long, item> itemMap = itemList.stream().collect(Collectors.toMap(Item::getId, i -> i,(k1, k2) -> k1));

//*其中第三个参数为键值重复处理策略,如果不传入第三个参数,当有相同的键时,会抛出一个IlleageStateException。*
//(k1, k2) -> k1)的作用是当有相同key存在时,留下Key1,舍弃Key2,不让程序报错。

//第二种写法
Map itemMap = itemList.stream().collect(Collectors.toMap(i ->i.id, i -> i,(k1, k2) -> k1));
//第三种写法
Map<String, Long> itemMap = itemList.stream().collect(Collectors.toMap(Item::getName,Item::getId, (k1, k2) -> k1));
//第四种写法
Map result = itemList.stream().collect(HashMap::new,(map,p)->map.put(p.name,p.id),Map::putAll);

.filter(),过滤出某一条数据。

Item match = items.stream() .filter((user) -> user.getId() == 3).findAny().get();

.distinct(),对list中的元素去重后重新组成列表。

//去重复
List<String> list = listTT.stream() .distinct().collect(toList());

toList()方法,将stream流中的元素都放置到一个列表集合中,默认这个列表是一个ArrayList,所以在声明变量的时候可以用List。当然类似的还有toSet(),同样的也是默认为HashSet。

List<String> ll = list.stream().collect(Collectors.toList());

joining(),将stream流中的元素串连接起来,可以指定连接符号,也可以不指定。

 // 指定连接符
        String lists = list.stream().collect(Collectors.joining("-"));