Apple apple01 = new Apple(1, "red", 100, "成都");
Apple apple02 = new Apple(2, "red", 99, "成都");
Apple apple03 = new Apple(3, "orange", 120, "西安");
Apple apple04 = new Apple(4, "orange", 80, "天津");
Apple apple05 = new Apple(5, "orange", 80, "深圳");
Apple apple06 = new Apple(6, "black", 102, "成都");
Apple apple07 = new Apple(7, "black", 99, "成都");
List<Apple> apples = new ArrayList<>();
Collections.addAll(apples, apple01, apple02, apple03, apple04, apple05, apple06, apple07);
//先按照奇数偶数分组,再按照地名分组
Map<String, Map<String, List<Apple>>> collect = apples.stream()
.collect(Collectors.groupingBy(x -> {
if ((x.getId() & 1) == 1) {
return "奇数";
} else {
return "偶数";
}
}, Collectors.groupingBy(Apple::getOroigin)));
System.out.println(collect);
打印结果如下:
{
偶数 = {
成都 = [
Apple {id = 2, colour = 'red', weight = 99, oroigin = '成都'},
Apple {id = 6, colour = 'black', weight = 102, oroigin = '成都'}
],
天津 = [
Apple {id = 4, colour = 'orange', weight = 80, oroigin = '天津'}
]
},
奇数 = {
成都 = [
Apple {id = 1, colour = 'red', weight = 100, oroigin = '成都'},
Apple {id = 7, colour = 'black', weight = 99, oroigin = '成都'}
],
西安 = [
Apple {id = 3, colour = 'orange', weight = 120, oroigin = '西安'}
],
深圳 = [
Apple {id = 5, colour = 'orange', weight = 80, oroigin = '深圳'}
]
}
}