gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:36:36 25 4
gpt4 key购买 nike

您好,我有一个对象数组,其中类别和子类别详细信息位于同一个对象中。所以它就像,

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));

最佳答案

如果将 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())));

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

关于java - 我可以按属性分组并映射到 Java 8 中的新对象吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53832444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com