@Test
public void lamdbaTest() {
List<Demo> list = new ArrayList<>();
list.add(new Demo(1, 2));
list.add(new Demo(3, 2));
list.add(new Demo(6, 1));
list.add(new Demo(2, 2));
list.add(new Demo(4, 2));
list.add(new Demo(5, 1));
list.add(new Demo(8, 1));
list.add(new Demo(7, 1));
list.add(new Demo(9, 3));
Map<Integer, Demo> map = new HashMap<>();
Stream<Demo> peek = list.stream().peek(demo -> map.put(demo.getId(), demo));
// 分组
Map<Integer, List<Demo>> collect = list.stream().collect(
groupingBy(Demo::getOutId)
);
// 分组排序
Map<Integer, List<Demo>> collectSort = list.stream().collect(
groupingBy(Demo::getOutId,
collectingAndThen(toList(),
l -> {
Collections.sort(l, Comparator.comparingInt(Demo::getId));
return l;
}))
);
// 分组排序 分会排序字段
Map<Integer, List<Integer>> collectSortInt = list.stream().collect(
groupingBy(Demo::getOutId,
mapping(Demo::getId, collectingAndThen(toList(),
l -> {
Collections.sort(l);
return l;
}))));
// 创建map
Map<Integer, Demo> demoMap = list.stream()
.collect(Collectors.toMap(Demo::getId, demo -> demo));
// 过滤
List<Demo> filter = list.stream().filter(demo -> demo.getId() > 3)
.collect(Collectors.toList());
//第一个大于3的
Demo filterFirst = list.stream().filter(demo -> demo.getId() > 3).findFirst().orElse(null);
// 求数量
long count = list.stream().filter(demo -> demo.getId() > 3).count();
// 分组最大的ID对象
Map<Integer, Demo> max = list.stream().collect(
groupingBy(Demo::getOutId,
collectingAndThen(maxBy(Comparator.comparing(Demo::getId)),
Optional::get)));
// 分组最大的ID
Map<Integer, Integer> maxInt = list.stream().collect(
groupingBy(Demo::getOutId,
collectingAndThen(maxBy(Comparator.comparing(Demo::getId)),
option -> option.get().getId())));
// 分组mapMap
Map<Integer, Map<Integer, Demo>> mapMap = list.stream().collect(
groupingBy(Demo::getOutId,
toMap(Demo::getId, demo -> demo)));
int[] ints = IntStream.builder().add(1).build().toArray();
Demo maxDemo = Collections.max(list, Comparator.comparing(Demo::getId));
List<Demo> sorted = list.stream().sorted(Comparator.comparing(Demo::getId))
.collect(Collectors.toList());
List<Demo> sortedLimit = list.stream().sorted(Comparator.comparing(Demo::getId))
.limit(3)
.collect(Collectors.toList());
// 求和
int sum = list.stream().mapToInt(Demo::getId).sum();
// 求和
int sum1 = list.stream().mapToInt(Demo::getId)
.reduce(Integer::sum)
.orElse(0);
// 求最大值
int sum2 = list.stream().mapToInt(Demo::getId)
.reduce(Integer::max)
.orElse(0);
// 洗牌
Collections.shuffle(list);
// 截取列表
List<Demo> subList = list.subList(3, 5);
System.out.println("12345678");
}
2019-06-20 集合操作lamdba
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 某一特定时间段,你会发现自己挺失败的。或者说,以世俗的眼光来看,就是瞎折腾。而,何谓成功呢?赚更多的钱,有更...
- 1.apache 操作 sudo /usr/sbin/apachectl start sudo /usr/sbin...