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)]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM