基础
//collect(toList()) 方法由 Stream 里的值生成一个列表
Stream.of("a", "b", "c").collect(Collectors.toList())
//一种类型的值转换成另外一种类型
Stream.of("a", "b", "c").map(e->e.toUpperCase()).collect(Collectors.toList())
//遍历数据并检查其中的元素
Stream.of("a", "b", "c").filter(e->e.equals("a")).collect(Collectors.toList())
//flatMap 方法可用 Stream 替换值,然后将多个 Stream 连接成一个 Stream
Stream.of(Arrays.asList("a", "b"),Arrays.asList("c", "d")).flatMap(e->e.stream()).collect(Collectors.toList())
//min 查找最小
List<User> users=new ArrayList<>()
users.add(new User("jack",1))
users.add(new User("tom",2))
User user = users.stream().min(Comparator.comparing(e -> e.getAge())).get()
//reduce 操作可以实现从一组值中生成一个值
Stream.of(1, 2, 3).reduce(0,(acc,e)->acc+e)
BinaryOperator<Integer> accumulator = (acc, element) -> acc + element
//reduce 展开
int count = accumulator.apply(
accumulator.apply(
accumulator.apply(0, 1),
2), 3)
//summaryStatistics 统计
IntSummaryStatistics trackLengthStats
= album.getTracks()
.mapToInt(track -> track.getLength())
.summaryStatistics()
System.out.printf("Max: %d, Min: %d, Ave: %f, Sum: %d",
trackLengthStats.getMax(),
trackLengthStats.getMin(),
trackLengthStats.getAverage(),
trackLengthStats.getSum())
重构案例
public Set<String> findLongTracks(List<Album> albums) {
Set<String> trackNames = new HashSet<>();
for(Album album : albums) {
for (Track track : album.getTrackList()) {
if (track.getLength() > 60) {
String name = track.getName();
trackNames.add(name);
}
}
}
return trackNames;
}
public Set<String> findLongTracks(List<Album> albums) {
return albums.stream().flatMap(album -> album.getTracks())
.filter(track -> track.getLength() > 60)
.map(track -> track.getName())
.collect(toSet());
}