1

I'm gonna give a little example of what i need. I have this simple beans:

public class Item {
   
    private String name;
    private String code;
    private Category category;
   
   //getters and setters omitted for brevity
}

public class SimpleItem {
   
    private String name;
    private String code;
   
   //getters and setters omitted for brevity
}

I need to map and group a Collection<Item> to a Map<Category,List<SimpleItem>>. I tried something like this

public class itemMapper {

    public Map<Category,List<SimpleItem>> map(Collection<Item> items){
        return items.stream()
                    .map(this::mapToSimpleItem)
                    .collect(groupingBy(Item::getCategory));
    }
    
    private SimpleItem mapToSimpleItem(Item item){
        //
    }
    
}

The problem is that after the mapping, the field category no longer exists. Any ideas?

1 Answers1

2

To get what you want you need to use groupingBy with mapping and not map before the collect, because as I said in comment, .map(this::mapToSimpleItem) return Stream<SimpleItem> and not Stream<Item>, your code should be:

return items.stream()
        .collect(groupingBy(Item::getCategory, 
                mapping(this::mapToSimpleItem, Collectors.toList())));
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140