I have
List<Gift> gifts = new ArrayList<>();
gifts .add(new Gift().withType(INF, CHD));
gifts .add(new Gift().withType(ADT, CHD));
gifts .add(new Gift().withType(INF, ADT));
Gift has a method List<Type> getTypes();
and now I want to convert the gift list to something like
Map<Type,List<Gift>>. I would like to do this with Java 8 and lambdas on the same line. Is it possible?
public class Gift {
public List<Type> getTypes() {
return types;
}
public Gift withType(Type... types) {
this.types = Arrays.asList(types);
return this;
}
List<Type> types = new ArrayList<>();
}
public enum Type {
ADT,
CHD,
INF;
}
Previous old code (it looks awful). That's all I have.
Map<Type, List<Gift>> byTypes = new HashMap<>();
for (Gift gift : gifts) {
for (Type type : gift.getTypes()) {
List<Gift> giftList = byTypes.get(type);
if (giftList == null) {
giftList = new ArrayList<>();
}
giftList.add(gift);
byTypes.put(type,giftList);
}
}
source
share