跳至主要內容

Java8使用Stream

牧歌...小于 1 分钟

Java8使用Stream

Java8 Stream排序空字段排在前面或后面

直接粗暴sorted会NPE,这种写法可以避免

list.stream().sorted(Comparator.comparing(l -> l.getCreateTime(), Comparator.nullsFirst(Date::compareTo))).collect(toList());

toOrderList.stream().sorted(Comparator.comparing(l -> l.getContractCode(), Comparator.nullsFirst(String::compareTo))).collect(toList());

Java8根据某字段顺序和倒序排列

顺序

resultList.stream().sorted(Comparator.comparing(Role::getCreateTime)).collect(Collectors.toList());

倒序

resultList.stream().sorted(Comparator.comparing(Role::getCreateTime).reversed()).collect(Collectors.toList());

分组Collectors.groupingBy()

public static void main(String[] args) {
	List<Student> list = new ArrayList<>();
	Student s1 = new Student("wwl","北京","公司1");
	Student s2 = new Student("wwl2","北京","公司2");
	Student s3 = new Student("wwl3","深圳","公司1");
	Student s4 = new Student("wwl4","深圳","公司3");
	Student s5 = new Student("wwl5","北京","公司1");
	list.add(s1);
	list.add(s2);
	list.add(s3);
	list.add(s4);
	list.add(s5);
	// 先按城市排序,再按公司排序
	Map<String, Long> collect = list.stream()
			// 中间用“_”隔开
			.collect(Collectors.groupingBy(o -> o.getCity() + "_" + o.getCompany(), Collectors.counting()));

	// 取数据
	List<DataInfo> countRecords = collect.keySet().stream().map(key -> {
		String[] temp = key.split("_");
		String cityName = temp[0];
		String company = temp[1];

		DataInfo record = new DataInfo();
		// 分组条件1
		record.setCity(cityName);
		// 分组条件2
		record.setCompany(company);
		// 统计的数量
		record.setCount(collect.get(key).intValue());
		return record;
	}).collect(Collectors.toList());
	System.out.println(collect);
	System.out.println(countRecords);
}
评论
  • 按正序
  • 按倒序
  • 按热度