Stream.of

将接收到的值转化为Stream。

对于List,可以用List.stream,对于Array,可以用Arrays.stream()。

  1. List<Integer> list = Arrays.asList(1,2,3,4);
  2. Stream<List<Integer>> stream = Stream.of(list);
  3. stream.forEach(str -> {System.out.println(str);});
  4. >> [1, 2, 3, 4]
  1. Set<String> origins=album.getMusicians()
  2. .filter(artist-> artist.getName().startsWith("The"))
  3. .map(artist-> artist.getNationality())
  4. .collect(toSet());

Stream中参数传入Lambda表达式时,会进行类型推断,当然也可以显示声明类型。

String转stream:

  1. hello.chars()
  2. .mapToObj(i -> (char)i)

collect

将Stream里的值生成一个列表。

  1. List<String> collected=Stream.of("a", "b", "hello")
  2. .map(string-> string.toUpperCase())
  3. .collect(toList());
  4. assertEquals(asList("A", "B", "HELLO"), collected);

averagingInt

  1. public double averageNumberOfTracks(List<Album> albums) {
  2. return albums.stream()
  3. .collect(averagingInt(album-> album.getTrackList().size()));
  4. }

partitioningBy

partitioningBy返回一个true和false的map,分别对应满足和不满足条件的list。

  1. public Map<Boolean, List<Artist>> bandsAndSolo(Stream<Artist> artists) {
  2. return artists.collect(partitioningBy(artist-> artist.isSolo()));
  3. }
  4. // 通过方法引用调用函数
  5. public Map<Boolean, List<Artist>> bandsAndSoloRef(Stream<Artist> artists) {
  6. return artists.collect(partitioningBy(Artist::isSolo));
  7. }

groupingBy

  1. public Map<Artist, List<Album>> albumsByArtist(Stream<Album> albums) {
  2. return albums.collect(groupingBy(album-> album.getMainMusician()));
  3. }

maxBy

  1. private static Comparator<Artist> byNameLength = comparing(artist -> artist.getName().length());
  2. public static Artist byReduce(List<Artist> artists) {
  3. return artists.stream()
  4. .reduce((acc, artist) -> {
  5. return (byNameLength.compare(acc, artist) >= 0) ? acc : artist;
  6. })
  7. .orElseThrow(RuntimeException::new);
  8. }
  9. public static Artist byCollecting(List<Artist> artists) {
  10. return artists.stream()
  11. .collect(Collectors.maxBy(byNameLength))
  12. .orElseThrow(RuntimeException::new);
  13. }

joining

将得到的艺术家名字连接为一个字符串。

  1. String result= artists.stream()
  2. .map(Artist::getName)
  3. .collect(Collectors.joining(", ", "[", "]"));

counting

返回每组的元素数。

  1. public Map<Artist, Long> numberOfAlbums(Stream<Album> albums) {
  2. return albums.collect(groupingBy(album-> album.getMainMusician(),
  3. counting()));
  4. }

mapping

mapping允许在收集器的容器上执行类似map的操作,但需要指明使用什么样的集合类存储结果(toList)。在示例代码中,mapping作为主收集器的下游收集器,对主收集器的每个子集进行map操作。

  1. public Map<Artist, List<String>> nameOfAlbums(Stream<Album> albums) {
  2. return albums.collect(groupingBy(Album::getMainMusician,
  3. mapping(Album::getName, toList())));
  4. }

filter

过滤Stream中元素,是惰性求值方法。Filter内的表达式必须返回True或False。

  1. List<String> beginningWithNumbers = Stream.of("a", "1abc", "abc1")
  2. .filter(value-> isDigit(value.charAt(0)))
  3. .collect(toList());

flatMap/map

将Stream中每个元素生成一个新的Stream流,用于将多个Stream连接成一个Stream。

  1. List<Integer> together=Stream.of(asList(1, 2), asList(3, 4))
  2. .flatMap(numbers-> numbers.stream())
  3. .collect(toList());
  4. assertEquals(asList(1, 2, 3, 4), together);

map:将返回结果转移成另一种形式。

  1. albums.stream()
  2. .flatMap(album-> album.getTracks()) // 因为一个album对应多个track,因此需要flatMap
  3. .filter(track-> track.getLength() > 60)
  4. .map(track-> track.getName())
  5. .collect(toSet());

min/max

min函数里需要提供一个Comparator对象。

  1. List<Track> tracks=asList(new Track("Bakai", 524),
  2. new Track("Violets for Your Furs", 378),
  3. new Track("Time Was", 451));
  4. Track shortestTrack=tracks.stream()
  5. .min(Comparator.comparing(track-> track.getLength()))
  6. .get();
  7. assertEquals(tracks.get(1), shortestTrack);

reduce

从一组值中生成一个值。
reduce中的第一个值是初值,,acc是累积结果。

  1. int count=Stream.of(1, 2, 3)
  2. .reduce(0, (acc, element)-> acc+element);
  3. assertEquals(6, count);

sum

  1. Integer res = Stream.of(1,2,3,6,7).mapToInt(x->x).sum();

mapTO

IntStream、DoubleStream、LongStream是经过特殊处理的Stream,针对基本类型进行了优化。

  1. IntSummaryStatistics trackLengthStats
  2. =album.getTracks()
  3. .mapToInt(track-> track.getLength())
  4. .summaryStatistics();
  5. System.out.printf("Max: %d, Min: %d, Ave: %f, Sum: %d",
  6. trackLengthStats.getMax(),
  7. trackLengthStats.getMin(),
  8. trackLengthStats.getAverage(),
  9. trackLengthStats.getSum());

count

  1. long c = numList.stream().count();

forEach

  1. Map<Artist, Integer> countOfAlbums=new HashMap<>();
  2. albumsByArtist.forEach((artist, albums)-> {
  3. countOfAlbums.put(artist, albums.size());
  4. });

computeIfAbsent

为map提供的操作,若找到key值则直接返回,若未找到,则进行lambda计算。

  1. private final Map<Integer,Long> cache;
  2. public Fibonacci() {
  3. cache = new HashMap<>();
  4. cache.put(0, 0L);
  5. cache.put(1, 1L);
  6. }
  7. public long fibonacci(int x) {
  8. return cache.computeIfAbsent(x, n -> fibonacci(n-1) + fibonacci(n-2));
  9. }

peek

peek能让你查看每个值的同时能继续操作流。

  1. Set<String> nationalities
  2. =album.getMusicians()
  3. .filter(artist-> artist.getName().startsWith("The"))
  4. .map(artist-> artist.getNationality())
  5. .peek(nation-> System.out.println("Found nationality: "+nation))
  6. .collect(Collectors.<String>toSet());

并行

将Stream换成parallelStream。

  1. public int parallelArraySum() {
  2. return albums.parallelStream()
  3. .flatMap(Album::getTracks)
  4. .mapToInt(Track::getLength)
  5. .sum();
  6. }
  • 性能好

ArrayList、数组或IntStream.range,这些数据结构支持随机读取,也就是说它们能轻而易举地被任意分解。

  • 性能一般

HashSet、TreeSet,这些数据结构不易公平地被分解,但是大多数时候分解是可能的。

  • 性能差

有些数据结构难于分解,比如,可能要花O(N)的时间复杂度来分解问题。其中包括LinkedList,对半分解太难了。还有Streams.iterate和BufferedReader.lines,它们长度未知,因此很难预测该在哪里分解。

封装

  1. public long countFeature(ToLongFunction<Album> function) {
  2. return albums.stream()
  3. .mapToLong(function)
  4. .sum();
  5. }
  6. public long countTracks() {
  7. return countFeature(album-> album.getTracks().count());
  8. }
  9. public long countRunningTime() {
  10. return countFeature(album-> album.getTracks()
  11. .mapToLong(track-> track.getLength())
  12. .sum());
  13. }
  14. public long countMusicians() {
  15. return countFeature(album-> album.getMusicians().count());
  16. }

lambda命令者模式

  1. public interface Editor {
  2. public void save();
  3. public void open();
  4. public void close();
  5. }
  1. public class Open implements Action {
  2. private final Editor editor;
  3. public Open(Editor editor) {
  4. this.editor=editor;
  5. }
  6. @Override
  7. public void perform() {
  8. editor.open();
  9. }
  10. }
  1. public class Macro {
  2. private final List<Action> actions;
  3. public Macro() {
  4. actions=new ArrayList<>();
  5. }
  6. public void record(Action action) {
  7. actions.add(action);
  8. }
  9. public void run() {
  10. actions.forEach(Action::perform);
  11. }
  12. }
  1. Macro macro=new Macro();
  2. macro.record(editor::open);
  3. macro.record(editor::save);
  4. macro.record(editor::close);
  5. macro.run();