高级集合——分片

分片

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 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> bandsResult = bandsAndSolo(example);
            
            bandsResult.forEach(
                    (x,y)->{System.out.println(x);
                            System.out.println(y);});
    }
    
    /**分成两波。true的为一波,其他的为另一波。函数接口是Predicate**/
    public static Map> bandsAndSolo(Stream artists) {
        return artists.collect(partitioningBy(Artist::isSolo));
    }
    
    public static Map> albumsByArtist(Stream albums) {
        /**group, 函数接口为function**/
        return albums.collect(groupingBy(Album::getMainMusician));
    }
}

2.输出结果

false
[haha, haha2]
true
[haha1]

你可能感兴趣的:(高级集合——分片)