分片
1.代码
package org.java8.collector;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.partitioningBy;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import org.java8.vo.Album;
import org.java8.vo.Artist;
public class StreamSplit {
public static void main(String[] args) {
Stream<Artist> example = Stream.of(
new Artist(
"haha",
Arrays.asList(new Artist("haha", "mei")),
"mei"),
new Artist(
"haha1",
Arrays.asList(),
"mei1"),
new Artist(
"haha2",
Arrays.asList(
new Artist("haha", "mei"),
new Artist("haha", "mei")),
"mei1")
);
Map<Boolean, List<Artist>> bandsResult = bandsAndSolo(example);
bandsResult.forEach(
(x,y)->{System.out.println(x);
System.out.println(y);});
}
/**分成两波。true的为一波,其他的为另一波。函数接口是Predicate**/
public static Map<Boolean, List<Artist>> bandsAndSolo(Stream<Artist> artists) {
return artists.collect(partitioningBy(Artist::isSolo));
}
public static Map<Artist, List<Album>> albumsByArtist(Stream<Album> albums) {
/**group, 函数接口为function**/
return albums.collect(groupingBy(Album::getMainMusician));
}
}
2.输出结果
false
[haha, haha2]
true
[haha1]