我可以按属性分组并映射到java 8中的新对象

jon*_*esy 5 java java-8

嗨我有一个对象数组,其中类别和子类别详细信息在同一个对象中.就像它一样,

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"));
Run Code Online (Sandbox Code Playgroud)

您是否可以按类别代码进行分组,但可以同时映射到包含描述的对象.所以,如果我有两个类,如..

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

..我想把收藏清单分成一个Map<Category,List<SubCategory>>.我可以对类别代码进行分组,但我看不到如何创建新的类别实例作为地图密钥.这在一个衬里中可能是不可能的.

Map<String, List<MyObject>> map = collection.stream().collect(Collectors.groupingBy(MyObject::getCategoryCode));
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 6

如果将mapping收集器链接到groupingBy.

您用于mapping()MyObject实例转换为SubCategory实例。

Map<Category,List<SubCategory>> map =
    collection.stream().collect(Collectors.groupingBy(mo -> new Category(mo.getCategoryCode(),mo.getCategoryDesc()),
                                                      Collectors.mapping(mo->new SubCategory(mo.getSubCategoryCode(),mo.getSubCategoryDesc()),
                                                                         Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)

请注意,Category必须覆盖equalsandhashCode才能使此分组起作用。