首页  

Java8 Stream API 实例 实现 list 分组     所属分类 java 浏览量 136
Map< String, List< Data>> groupedByKey1 = list.stream().collect(Collectors.groupingBy (Data::getKey1));




import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;


public class GroupTest {
    public static void main(String[] args) {
        List<Data> list = new ArrayList<>();
        Data data = new Data(1, "a", "b");
        list.add(data);
        data = new Data(2, "a", "b");
        list.add(data);
        data = new Data(3, "a1", "b");
        list.add(data);
		
        Function<Data, String> f = new Function<Data, String>() {
            @Override
            public String apply(Data data) {
                return data.key1;
            }
        };
        Map<String, List<Data>> map = groupBy(list, f);
        System.out.println(map);

        // 只能引用方法 不能引用字段
        map = groupBy(list, Data::getKey1);
        System.out.println(map);

        map = groupBy(list, Data::getKey2);
        System.out.println(map);
		
        Map<String, List<Data>> groupedByKey1 = list.stream()
                .collect(Collectors.groupingBy(Data::getKey1));

        System.out.println(groupedByKey1);

        Map<String, List<Data>> map2 = groupBy(list, Data::getKey1);
        System.out.println(map2);
    }


    public static <T> Map<String, List<T>> groupBy(List<T> list, Function<T, String> func) {
        Map<String, List<T>> dataMap = new HashMap<>();
        for (T item : list) {
            String key = func.apply(item);
            List<T> groupList = dataMap.get(key);
            if (groupList == null) {
                groupList = new ArrayList<>();
                dataMap.put(key, groupList);
            }
            groupList.add(item);
        }
        return dataMap;
    }


    public static class Data {
        public final int id;
        public final String key1;
        public final String key2;

        public Data(int id, String key1, String key2) {
            this.id = id;
            this.key1 = key1;
            this.key2 = key2;
        }

        public String getKey1() {
            return key1;
        }

        public String getKey2() {
            return key2;
        }
		
        @Override
        public String toString() {
            return "Data{" +
                    "id=" + id +
                    ", key1='" + key1 + '\'' +
                    ", key2='" + key2 + '\'' +
                    '}';
        }
    }
	
}



上一篇     下一篇
小学奥数术语

小学数学应用题

几何常见解题方法

tan15度计算

mybatisplus 逻辑删除

经典儿童英语诗歌