Partition a Stream by a discriminator function

前端 未结 3 691
有刺的猬
有刺的猬 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

    It can be done by collapse with StreamEx

    StreamEx.of(queryBuilder.createQuery(
        "SELECT f.name, m.name"
        + " FROM Family f JOIN Member m on m.family_id = f.id"
        + " ORDER BY f.name"))
            .collapse((a, b) -> a.string(0).equals(b.string(0)), Collectors.toList())
            .map(l -> new Family(l.get(0).string(0), StreamEx.of(l).map(r -> r.string(1)).toList())) 
            .forEach(System.out::println);
    

提交回复
热议问题