Lovegiver:
私は、ストリーム&ラムダカップルを使用して地図を構築したいと思います。
私は多くの方法を試みたが、私はstuckedです。ここでストリーム/ラムダと古典的なループの両方を使用してそれを行うには、古典的なJavaコードです。
Map<Entity, List<Funder>> initMap = new HashMap<>();
List<Entity> entities = pprsToBeApproved.stream()
.map(fr -> fr.getBuyerIdentification().getBuyer().getEntity())
.distinct()
.collect(Collectors.toList());
for(Entity entity : entities) {
List<Funder> funders = pprsToBeApproved.stream()
.filter(fr -> fr.getBuyerIdentification().getBuyer().getEntity().equals(entity))
.map(fr -> fr.getDocuments().get(0).getFunder())
.distinct()
.collect(Collectors.toList());
initMap.put(entity, funders);
}
あなたが見ることができるように、私はリストのみで収集する方法を知っているが、私はちょうどマップと同じことを行うことはできません。私は、最終的に第二のリストを構築するマップですべて一緒に入れて、再び私のリストをストリーミングするために持っている理由です。また、私はそれがあまりにもマップを生成しなければならないとして、「collect.groupingBy」ステートメントを試してみたが、私は失敗しました。
フェデリコ・ペラルタシャフナー:
あなたが上にあるものは何でもマップしたいと思われるpprsToBeApproved
あなたのリストFunder
のバイヤーによってそれらをグループ化し、インスタンスEntity
。
次のようにあなたはそれを行うことができます。
Map<Entity, List<Funder>> initMap = pprsToBeApproved.stream()
.collect(Collectors.groupingBy(
fr -> fr.getBuyerIdentification().getBuyer().getEntity(), // group by this
Collectors.mapping(
fr -> fr.getDocuments().get(0).getFunder(), // mapping each element to this
Collectors.toList()))); // and putting them in a list
あなたが特定のエンティティの重複資金提供者をしたくない場合は、代わりにセットのマップに収集できます。
Map<Entity, Set<Funder>> initMap = pprsToBeApproved.stream()
.collect(Collectors.groupingBy(
fr -> fr.getBuyerIdentification().getBuyer().getEntity(),
Collectors.mapping(
fr -> fr.getDocuments().get(0).getFunder(),
Collectors.toSet())));
これは、使用していますCollectors.groupingBy
と一緒にCollectors.mapping
。