Stream.of
将接收到的值转化为Stream。
对于List,可以用List.stream,对于Array,可以用Arrays.stream()。
List<Integer> list = Arrays.asList(1,2,3,4);Stream<List<Integer>> stream = Stream.of(list);stream.forEach(str -> {System.out.println(str);});>> [1, 2, 3, 4]
Set<String> origins=album.getMusicians().filter(artist-> artist.getName().startsWith("The")).map(artist-> artist.getNationality()).collect(toSet());
Stream中参数传入Lambda表达式时,会进行类型推断,当然也可以显示声明类型。
String转stream:
hello.chars().mapToObj(i -> (char)i)
collect
将Stream里的值生成一个列表。
List<String> collected=Stream.of("a", "b", "hello").map(string-> string.toUpperCase()).collect(toList());assertEquals(asList("A", "B", "HELLO"), collected);
averagingInt
public double averageNumberOfTracks(List<Album> albums) {return albums.stream().collect(averagingInt(album-> album.getTrackList().size()));}
partitioningBy
partitioningBy返回一个true和false的map,分别对应满足和不满足条件的list。
public Map<Boolean, List<Artist>> bandsAndSolo(Stream<Artist> artists) {return artists.collect(partitioningBy(artist-> artist.isSolo()));}// 通过方法引用调用函数public Map<Boolean, List<Artist>> bandsAndSoloRef(Stream<Artist> artists) {return artists.collect(partitioningBy(Artist::isSolo));}
groupingBy
public Map<Artist, List<Album>> albumsByArtist(Stream<Album> albums) {return albums.collect(groupingBy(album-> album.getMainMusician()));}
maxBy
private static Comparator<Artist> byNameLength = comparing(artist -> artist.getName().length());public static Artist byReduce(List<Artist> artists) {return artists.stream().reduce((acc, artist) -> {return (byNameLength.compare(acc, artist) >= 0) ? acc : artist;}).orElseThrow(RuntimeException::new);}public static Artist byCollecting(List<Artist> artists) {return artists.stream().collect(Collectors.maxBy(byNameLength)).orElseThrow(RuntimeException::new);}
joining
将得到的艺术家名字连接为一个字符串。
String result= artists.stream().map(Artist::getName).collect(Collectors.joining(", ", "[", "]"));
counting
返回每组的元素数。
public Map<Artist, Long> numberOfAlbums(Stream<Album> albums) {return albums.collect(groupingBy(album-> album.getMainMusician(),counting()));}
mapping
mapping允许在收集器的容器上执行类似map的操作,但需要指明使用什么样的集合类存储结果(toList)。在示例代码中,mapping作为主收集器的下游收集器,对主收集器的每个子集进行map操作。
public Map<Artist, List<String>> nameOfAlbums(Stream<Album> albums) {return albums.collect(groupingBy(Album::getMainMusician,mapping(Album::getName, toList())));}
filter
过滤Stream中元素,是惰性求值方法。Filter内的表达式必须返回True或False。
List<String> beginningWithNumbers = Stream.of("a", "1abc", "abc1").filter(value-> isDigit(value.charAt(0))).collect(toList());
flatMap/map
将Stream中每个元素生成一个新的Stream流,用于将多个Stream连接成一个Stream。
List<Integer> together=Stream.of(asList(1, 2), asList(3, 4)).flatMap(numbers-> numbers.stream()).collect(toList());assertEquals(asList(1, 2, 3, 4), together);
map:将返回结果转移成另一种形式。
albums.stream().flatMap(album-> album.getTracks()) // 因为一个album对应多个track,因此需要flatMap.filter(track-> track.getLength() > 60).map(track-> track.getName()).collect(toSet());
min/max
min函数里需要提供一个Comparator对象。
List<Track> tracks=asList(new Track("Bakai", 524),new Track("Violets for Your Furs", 378),new Track("Time Was", 451));Track shortestTrack=tracks.stream().min(Comparator.comparing(track-> track.getLength())).get();assertEquals(tracks.get(1), shortestTrack);
reduce
从一组值中生成一个值。
reduce中的第一个值是初值,,acc是累积结果。
int count=Stream.of(1, 2, 3).reduce(0, (acc, element)-> acc+element);assertEquals(6, count);
sum
Integer res = Stream.of(1,2,3,6,7).mapToInt(x->x).sum();
mapTO
IntStream、DoubleStream、LongStream是经过特殊处理的Stream,针对基本类型进行了优化。
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());
count
long c = numList.stream().count();
forEach
Map<Artist, Integer> countOfAlbums=new HashMap<>();albumsByArtist.forEach((artist, albums)-> {countOfAlbums.put(artist, albums.size());});
computeIfAbsent
为map提供的操作,若找到key值则直接返回,若未找到,则进行lambda计算。
private final Map<Integer,Long> cache;public Fibonacci() {cache = new HashMap<>();cache.put(0, 0L);cache.put(1, 1L);}public long fibonacci(int x) {return cache.computeIfAbsent(x, n -> fibonacci(n-1) + fibonacci(n-2));}
peek
peek能让你查看每个值的同时能继续操作流。
Set<String> nationalities=album.getMusicians().filter(artist-> artist.getName().startsWith("The")).map(artist-> artist.getNationality()).peek(nation-> System.out.println("Found nationality: "+nation)).collect(Collectors.<String>toSet());
并行
将Stream换成parallelStream。
public int parallelArraySum() {return albums.parallelStream().flatMap(Album::getTracks).mapToInt(Track::getLength).sum();}
- 性能好
ArrayList、数组或IntStream.range,这些数据结构支持随机读取,也就是说它们能轻而易举地被任意分解。
- 性能一般
HashSet、TreeSet,这些数据结构不易公平地被分解,但是大多数时候分解是可能的。
- 性能差
有些数据结构难于分解,比如,可能要花O(N)的时间复杂度来分解问题。其中包括LinkedList,对半分解太难了。还有Streams.iterate和BufferedReader.lines,它们长度未知,因此很难预测该在哪里分解。
封装
public long countFeature(ToLongFunction<Album> function) {return albums.stream().mapToLong(function).sum();}public long countTracks() {return countFeature(album-> album.getTracks().count());}public long countRunningTime() {return countFeature(album-> album.getTracks().mapToLong(track-> track.getLength()).sum());}public long countMusicians() {return countFeature(album-> album.getMusicians().count());}
lambda命令者模式
public interface Editor {public void save();public void open();public void close();}
public class Open implements Action {private final Editor editor;public Open(Editor editor) {this.editor=editor;}@Overridepublic void perform() {editor.open();}}
public class Macro {private final List<Action> actions;public Macro() {actions=new ArrayList<>();}public void record(Action action) {actions.add(action);}public void run() {actions.forEach(Action::perform);}}
Macro macro=new Macro();macro.record(editor::open);macro.record(editor::save);macro.record(editor::close);macro.run();
