Java8中Stream 的一些用法
阿新 • • 發佈:2020-10-20
資料結構和資料準備
@Data @AllArgsConstructor @NoArgsConstructor static class StreamItem { Integer id; String name; Boolean sex; } List<StreamItem> list = Lists.newArrayList(new StreamItem(1, "a", true), new StreamItem(2, "b", false), new StreamItem(3, "c", true), new StreamItem(1, "d", false), new StreamItem(4, "e", true));
map
List<String> list2 = list.stream().map(StreamItem::getName).collect(Collectors.toList());
System.out.println(list2);
[a, b, c, d, e]
groupingBy
Map<Integer, List<StreamItem>> list2 = list.stream().collect(Collectors.groupingBy(StreamItem::getId)); System.out.println(list2); {1=[StreamStudy.StreamItem(id=1, name=a, sex=true), StreamStudy.StreamItem(id=1, name=d, sex=false)], 2=[StreamStudy.StreamItem(id=2, name=b, sex=false)], 3=[StreamStudy.StreamItem(id=3, name=c, sex=true)], 4=[StreamStudy.StreamItem(id=4, name=e, sex=true)]}
toMap
Map<Integer, String> list2 = list.stream().collect(Collectors.toMap(StreamItem::getId, StreamItem::getName, (k1, k2) -> k2));
System.out.println(list2);
{1=d, 2=b, 3=c, 4=e}
filter
List<StreamItem> list2 = list.stream().filter(StreamItem::getSex).collect(Collectors.toList()); System.out.println(list2); [StreamStudy.StreamItem(id=1, name=a, sex=true), StreamStudy.StreamItem(id=3, name=c, sex=true), StreamStudy.StreamItem(id=4, name=e, sex=true)]
sum
int sum = list.stream().mapToInt(StreamItem::getId).sum();
System.out.println(sum);
sum = list.stream().map(StreamItem::getId).reduce(Integer::sum).get();
System.out.println(sum);
sum = list.stream().map(StreamItem::getId).reduce(0, Integer::sum);
System.out.println(sum);
BigDecimal bigDecimal = list.stream()
.map(streamItem -> new BigDecimal(streamItem.getId()))
.reduce(BigDecimal.ZERO, BigDecimal::add);
System.out.println(bigDecimal);
11
11
11
11
參考
使用Stream快速對List進行一些操作
Java8之Consumer、Supplier、Predicate和Function攻略