java strem 分组并提取对象中的某个字段

先上代码

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jnchen
 * @date 2021/3/10 11:11
 */
public class Demo {
    static class DemoClass {
        private Integer key;

        private String value;

        public DemoClass(Integer key, String value) {
            this.key = key;
            this.value = value;
        }

        public Integer getKey() {
            return key;
        }

        public String getValue() {
            return value;
        }
    }

    public static List generateList() {
        List list = new ArrayList<>();
        for (int i = 0; i < 50; i++) {
            list.add(new DemoClass((int) (Math.random() * 20), UUID.randomUUID().toString()));
        }
        return list;
    }

    public static void main(String[] args) {
        List list = generateList();
        Map> group = list.stream().collect(Collectors.groupingBy(DemoClass::getKey, Collectors.mapping(DemoClass::getValue, Collectors.toSet())));
        System.out.println(group);
    }
}

需求:我有一个对象,我要按照其中的某个字段分组成一个Map,并且分组的值为另一个字段的值

你可能感兴趣的:(Java,java,stream,lambda)