Java8之stream流的分组排序

关于Java8的stream流,这里不讲groupBy分组,也不讲sort排序,这些都是很基础的用法,可以自行百度。

这里说一种业务场景,对于分组后的map,根据value对key-value进行排序。举个例子,人(姓名,地址,创建时间)的集合,要求按地址将他们分组,同时要求越晚被创建的人,所在的分组越靠前。

直接上People类:

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class People {

    private String name;

    private String address;

    private Long createTime;

}

然后是分组排序代码:

	public static void main(String[] args) {
		long time = 1L;
		List<People> list = new ArrayList<>();
		list.add(new People("曹丕", "魏", time++));
		list.add(new People("关羽", "蜀", time++));
		list.add(new People("刘备", "蜀", time++));
		list.add(new People("小乔", "吴", time++));
		list.add(new People("周瑜", "吴", time++));
		list.add(new People("曹操", "魏", time++));

		Map<String, List<People>> collect = list.stream()
				.filter(d -> d != null && d.getAddress() != null) // 这里是为了下面分组的key不为null,要是key为null会报错的
				.sorted(Comparator.comparingLong(People::getCreateTime).reversed())
				.collect(Collectors.groupingBy(People::getAddress, LinkedHashMap::new, Collectors.toList()));

		for (Map.Entry<String, List<People>> entry : collect.entrySet()) {
			System.out.println(entry.getKey() + "\t" + entry.getValue());
		}
	}

最后是运行结果:

魏	[People(name=曹操, address=魏, createTime=6), People(name=曹丕, address=魏, createTime=1)]
吴	[People(name=周瑜, address=吴, createTime=5), People(name=小乔, address=吴, createTime=4)]
蜀	[People(name=刘备, address=蜀, createTime=3), People(name=关羽, address=蜀, createTime=2)]

那么如果按照题目要求,这个时候,我再加个“蜀国”人,那么这个人所在分组就应该放到第一的位置

		long time = 1L;
		List<People> list = new ArrayList<>();
		list.add(new People("曹丕", "魏", time++));
		list.add(new People("关羽", "蜀", time++));
		list.add(new People("刘备", "蜀", time++));
		list.add(new People("小乔", "吴", time++));
		list.add(new People("周瑜", "吴", time++));
		list.add(new People("曹操", "魏", time++));
		list.add(new People("张飞", "蜀", time++));

运行后结果如下,发现最后添加的“张飞”所在的“蜀”分类,已经放到了第一的位置:

蜀	[People(name=张飞, address=蜀, createTime=7), People(name=刘备, address=蜀, createTime=3), People(name=关羽, address=蜀, createTime=2)]
魏	[People(name=曹操, address=魏, createTime=6), People(name=曹丕, address=魏, createTime=1)]
吴	[People(name=周瑜, address=吴, createTime=5), People(name=小乔, address=吴, createTime=4)]
posted @ 2021-10-06 15:08  dijia478  阅读(11166)  评论(0编辑  收藏  举报