数据结构和数据准备
@Data
@AllArgsConstructor
@NoArgsConstructor
static class StreamItem {
Integer id;
String name;
Boolean sex;
}
List 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 list2 = list.stream().map(StreamItem::getName).collect(Collectors.toList());
System.out.println(list2);
[a, b, c, d, e]
groupingBy
Map> 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 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 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
sort
list.sort(Comparator.comparing(StreamItem::getName).reversed());
System.out.println(list);
根据name进行倒序排序
[StreamStudy.StreamItem(id=4, name=e, sex=true), StreamStudy.StreamItem(id=1, name=d, sex=false), StreamStudy.StreamItem(id=3, name=c, sex=true), StreamStudy.StreamItem(id=2, name=b, sex=false), StreamStudy.StreamItem(id=1, name=a, sex=true)]
foreach
list.forEach(streamItem -> streamItem.setId(streamItem.getId() + 1));
list.forEach(System.out::println);
StreamStudy.StreamItem(id=2, name=a, sex=true)
StreamStudy.StreamItem(id=3, name=b, sex=false)
StreamStudy.StreamItem(id=4, name=c, sex=true)
StreamStudy.StreamItem(id=2, name=d, sex=false)
StreamStudy.StreamItem(id=5, name=e, sex=true)
参考