public static void main(String[] args) {
List<Developer> listDevs = getDevelopers();
//lambda 按名称排序
listDevs.sort((Developer o1, Developer o2) -> o1.getName().compareTo(o2.getName()));
System.out.println("按名称排序:" + JSON.toJSONString(listDevs));
//lambda 按名称排序
listDevs.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
System.out.println("按名称排序:" + JSON.toJSONString(listDevs));
//lambda 按名称排序
listDevs.sort(Comparator.comparing(Developer::getName).reversed());
System.out.println("按名称排序:" + JSON.toJSONString(listDevs));
List<Developer> developersGroup = getDevelopersGroup();
//stream 按名称分组
Map<String, List<Developer>> developersGroupMap = developersGroup.stream().collect(Collectors.groupingBy(Developer::getName));
System.out.println("按名称分组:" + JSON.toJSONString(developersGroupMap));
List<Integer> ageList = new ArrayList<>();
ageList.add(20);
ageList.add(20);
ageList.add(10);
ageList.add(10);
ageList.add(11);
//stream 对list分组统计
Map<Integer, Long> collect = ageList.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("对list分组统计:" + JSON.toJSONString(collect));
}
private static List<Developer> getDevelopers() {
List<Developer> result = new ArrayList<Developer>();
result.add(new Developer("mkyong", new BigDecimal("70000"), 33));
result.add(new Developer("alvin", new BigDecimal("80000"), 20));
result.add(new Developer("jason", new BigDecimal("100000"), 10));
result.add(new Developer("iris", new BigDecimal("170000"), 55));
return result;
}
private static List<Developer> getDevelopersGroup() {
List<Developer> result = new ArrayList<Developer>();
result.add(new Developer("mkyong", new BigDecimal("70000"), 33));
result.add(new Developer("mkyong", new BigDecimal("80000"), 20));
result.add(new Developer("jason", new BigDecimal("100000"), 10));
result.add(new Developer("jason", new BigDecimal("170000"), 55));
return result;
}
输出结果
按名称排序:[{"age":20,"bigDecimal":80000,"name":"alvin"},{"age":55,"bigDecimal":170000,"name":"iris"},{"age":10,"bigDecimal":100000,"name":"jason"},{"age":33,"bigDecimal":70000,"name":"mkyong"}]
按名称排序:[{"age":20,"bigDecimal":80000,"name":"alvin"},{"age":55,"bigDecimal":170000,"name":"iris"},{"age":10,"bigDecimal":100000,"name":"jason"},{"age":33,"bigDecimal":70000,"name":"mkyong"}]
按名称排序:[{"age":33,"bigDecimal":70000,"name":"mkyong"},{"age":10,"bigDecimal":100000,"name":"jason"},{"age":55,"bigDecimal":170000,"name":"iris"},{"age":20,"bigDecimal":80000,"name":"alvin"}]
按名称分组:{"mkyong":[{"age":33,"bigDecimal":70000,"name":"mkyong"},{"age":20,"bigDecimal":80000,"name":"mkyong"}],"jason":[{"age":10,"bigDecimal":100000,"name":"jason"},{"age":55,"bigDecimal":170000,"name":"jason"}]}
对list分组统计:{20:2,10:2,11:1}
本文暂时没有评论,来添加一个吧(●'◡'●)