你好,我有一个对象数组,其中类别和子类别的详细信息在同一个对象中。所以它看起来像这样:
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"));
您是否可以按类别代码分组,同时将其映射到一个包括描述的对象中。例如,如果我有两个类似于...
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;
}
}
我希望将集合列表分组为一个Map<Category,List<SubCategory>>
。我可以按类别代码进行分组,但我不知道如何创建新的类别实例作为映射键。这可能无法在一行中完成。
Map<String, List<MyObject>> map = collection.stream().collect(Collectors.groupingBy(MyObject::getCategoryCode));
Collectors.mapping
又将再次发威... - Eugene