Java: how to transform from List to Map without iterating

前端 未结 4 1624
予麋鹿
予麋鹿 2020-12-30 03:56

I have a list of objects that I need to transform to a map where the keys are a function of each element, and the values are lists of another function of each element. Effec

4条回答
  •  别那么骄傲
    2020-12-30 04:58

    Now with Java8 you can do it like:

    static class Element {
        final int f1;
        final String f2;
    
        Element(int f1, String f2) {
            this.f1 = f1;
            this.f2 = f2;
        }
    
        int f1() { return f1;}
        String f2() { return f2; }
    }
    
    public static void main(String[] args) {
        List elements = new ArrayList<>();
        elements.add(new Element(100, "Alice"));
        elements.add(new Element(200, "Bob"));
        elements.add(new Element(100, "Charles"));
        elements.add(new Element(300, "Dave"));
    
        elements.stream()
                .collect(Collectors.groupingBy(
                        Element::f1,
                        Collectors.mapping(Element::f2, Collectors.toList())
                        ))
                .forEach((f1, f2) -> System.out.println("{"+f1.toString() + ", value="+f2+"}"));
    }
    

提交回复
热议问题