高级集合——组合收集器

组合收集器

1.代码

package org.java8.collector;

import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;

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;
import org.java8.vo.Track;

public class MultiCollector {

    /**逆向统计,根据值来统计key或者整个对象**/
    public static void main(String[] args) {
        Artist tinygao2 = new Artist("tinygao2", "zh");
        Artist tinygao1 = new Artist("tinygao1", "zh");
        
        Album album1 = new Album(
                                "album1", 
                                Arrays.asList(new Track("tinygao", 1)), 
                                Arrays.asList(
                                        tinygao2,
                                        tinygao1
                                ));
        
        Album album2= new Album(
                                "album2", 
                                Arrays.asList(new Track("tinygao", 1)), 
                                Arrays.asList(
                                        tinygao2,
                                        tinygao1
                                ));
        
        Album album3  = new Album(
                                "album3", 
                                Arrays.asList(new Track("tinygao", 1)), 
                                Arrays.asList(
                                        tinygao1
                                ));
        Stream albums1 = Stream.of(album1,album2,album3);
        Stream albums2 = Stream.of(album1,album2,album3);
        numberOfAlbums(albums1).forEach((x, y)->System.out.println(x+"->"+y));
        /**使用完流之后就会关闭, 再使用就会报错stream has already been operated upon or closed**/
        nameOfAlbums(albums2).forEach((x, y)->System.out.println(x+"->"+y));
        
    }
    
    public static Map numberOfAlbums(Stream albums) {
        /**先获取Artist function,然后在做reduce操作**/
        /** Map> 为下面的返回值
            albums.collect(groupingBy(album -> album.getMainMusician()));
        **/
        return albums.collect(groupingBy(album -> album.getMainMusician(),
                counting()));
    }
    
    public static Map> nameOfAlbums(Stream albums) {
        /**Album::getName 在mapping中是对Map> 后者做mapping**/
        return albums.collect(groupingBy(Album::getMainMusician,
        mapping(Album::getName, toList())));
    }
}

2.输出

tinygao1->1
tinygao2->2
tinygao1->[album3]
tinygao2->[album1, album2]

你可能感兴趣的:(高级集合——组合收集器)