Hi I have an array of objects where the category and sub category details are in the same object. So its like,
public class MyObject {
String categoryCode;
String categeoryCodeDescription;
String subCategoryCode;
String subCategoryCodeDescription;
public MyObject(String categoryCode, String categeoryCodeDescription, String subCategoryCode, String subCategoryCodeDescription) {
this.categoryCode = categoryCode;
this.categeoryCodeDescription = categeoryCodeDescription;
this.subCategoryCode = subCategoryCode;
this.subCategoryCodeDescription = subCategoryCodeDescription;
}
}
List<MyObject> collection = new ArrayList<MyObject>;
collection.add(new My Object("A1", "descA1", "A1A", "descA1A"));
collection.add(new My Object("A1", "descA1", "A1B", "descA1B"));
collection.add(new My Object("A1", "descA1", "A1C", "descA1C"));
collection.add(new My Object("A2", "descA1", "A2A", "descA2A"));
collection.add(new My Object("A2", "descA1", "A2B", "descA2B"));
Can you group by category code but map to an object including the description at the same time. So if I have two classes like..
public class Category {
String categoryCode;
String categoryDesc;
public Category (String categoryCode, String categoryDesc) {
this.categoryCode = categoryCode;
this.categoryDesc = categoryDesc;
}
}
public class SubCategory {
String subCategoryCode;
String subCategoryDesc;
public SubCategory (String subCategoryCode, String subCategoryDesc) {
this.subCategoryCode = subCategoryCode;
this.subCategoryDesc = subCategoryDesc;
}
}
..and I want to group the collection list into a Map<Category,List<SubCategory>>. I can group on the category code but I can't see how to create a new category instance as the map key. This may not be possible in a one liner.
Map<String, List<MyObject>> map = collection.stream().collect(Collectors.groupingBy(MyObject::getCategoryCode));