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

时间:2025-03-02 10:32:31

先上代码

import .*;
import ;

/**
 * @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) {
             = key;
             = value;
        }

        public Integer getKey() {
            return key;
        }

        public String getValue() {
            return value;
        }
    }

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

    public static void main(String[] args) {
        List<DemoClass> list = generateList();
        Map<Integer, Set<String>> group = ().collect((DemoClass::getKey, (DemoClass::getValue, ())));
        (group);
    }
}

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