Partition a Stream by a discriminator function

前端 未结 3 672
有刺的猬
有刺的猬 2020-12-05 05:19

One of the missing features in the Streams API is the \"partition by\" transformation, for example as defined in Clojure. Say I want to reproduce Hibernate\'s fetch join

3条回答
  •  有刺的猬
    2020-12-05 05:34

    For those of you who just want to partition a stream, there are mappers and collectors for that.

    class Person {
    
        String surname;
        String forename;
    
        public Person(String surname, String forename) {
            this.surname = surname;
            this.forename = forename;
        }
    
        @Override
        public String toString() {
            return forename;
        }
    
    }
    
    class Family {
    
        String surname;
        List members;
    
        public Family(String surname, List members) {
            this.surname = surname;
            this.members = members;
        }
    
        @Override
        public String toString() {
            return "Family{" + "surname=" + surname + ", members=" + members + '}';
        }
    
    }
    
    private void test() {
        String[][] data = {
            {"Kray", "Ronald"},
            {"Kray", "Reginald"},
            {"Dors", "Diana"},};
        // Their families.
        Stream families = Arrays.stream(data)
                // Build people
                .map(a -> new Person(a[0], a[1]))
                // Collect into a Map> as families
                .collect(Collectors.groupingBy(p -> p.surname))
                // Convert them to families.
                .entrySet().stream()
                .map(p -> new Family(p.getKey(), p.getValue()));
        families.forEach(f -> System.out.println(f));
    }
    

提交回复
热议问题