使用自定义密钥的Java收集分组
我有一个学生的列表studentList
,我想根据他们的班级和部分将它们分开,并将其分为map< customkey,list< student>>>
。
class Student {
public String Name;
public String Class;
public String Section;
}
我有一个自定义的密钥类,
class CustomKey {
public String Class;
public String Section;
}
我正在尝试使用此功能将它们分组,但是我们可以清楚地看到我做错了什么。
studentList.stream().collect(Collectors.groupingBy(x -> new CustomKey(x.Class, x.Section)));
组内的表达式不正确。 不允许扩展学生班:(
我想创建此输出,
{
{"ClassA", "SectionA"}: [{name, class, section}, {name, class, section}],
{"ClassA", "SectionB"}: [{name, class, section}],
{"ClassB", "SectionA"}: [{name, class, section}, {name, class, section}],
}
我的知识在Java上非常有限。任何帮助/指示都受到欢迎。 另外,对于混乱的案件表示歉意。
I have a list of students studentList
and i want to seperate them based on their class and section into a Map<CustomKey, List<Student>>
.
class Student {
public String Name;
public String Class;
public String Section;
}
I have a custom Key Class
class CustomKey {
public String Class;
public String Section;
}
I'm trying to group them using this, but we can clearly see what I'm doing wrong.
studentList.stream().collect(Collectors.groupingBy(x -> new CustomKey(x.Class, x.Section)));
The expression inside groupingBy is incorrect.
Extending the Student Class is not allowed :(
I want to create this output
{
{"ClassA", "SectionA"}: [{name, class, section}, {name, class, section}],
{"ClassA", "SectionB"}: [{name, class, section}],
{"ClassB", "SectionA"}: [{name, class, section}, {name, class, section}],
}
My knowledge is very limited on JAVA. And any help/pointers are welcomed.
Also, Apologies for the messed-up cases.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,
customKey
与其equals
方法匹配,而您没有被覆盖。如果您实现等于
(以及hashcode
),则它将起作用。更好的是,为
CustomKey
创建 record :这将使编译器自动生成其
等于
equals 和hashcode < /code>免费实现,以及getters canonical构造函数和
toString
方法。上述记录定义等同于此:Well,
CustomKey
is matched by itsequals
method, which you don't have overridden. If you implementequals
(and alsohashCode
) properly, then it'll work.What's even better, is to create a record for
CustomKey
:This'll let the compiler auto-generate its
equals
andhashCode
implementations for free, as well as getters, the canonical constructor and thetoString
method. The above record definition is equivalent to this:我完全像下面一样使用您的代码,它对我有用,
例如下面创建您的pojo
}}
}
output
i used your code exactly like below and it works for me
create your pojo like below
}
}
output