java – Collectors.groupingBy由两列不起作用
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – Collectors.groupingBy由两列不起作用,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2357字,纯文字阅读大概需要4分钟。
内容图文
我想使用Collectors.groupingBy将两列分组.
我写了以下内容:
public class TestGroupKey
{
public static void main(String... args) {
List<Item> list = Arrays.asList(
new Item(1, 1, 1),
new Item(1, 1, 2),
new Item(1, 1, 3),
new Item(1, 2, 1),
new Item(1, 2, 2),
new Item(2, 1, 1),
new Item(2, 2, 1),
new Item(2, 3, 1),
new Item(2, 4, 1),
new Item(2, 4, 2),
new Item(2, 4, 3),
new Item(2, 4, 4),
new Item(3, 1, 1),
new Item(3, 1, 2),
new Item(3, 1, 3),
new Item(3, 1, 4),
new Item(3, 2, 1),
new Item(3, 2, 2)
);
Map<CustomKey, List<Item>> tupleGrouping =
list.stream().collect(Collectors.groupingBy(item -> item.customKey));
tupleGrouping.entrySet().stream()
.forEach(entry -> {
System.out.println(entry.getKey());
});
}
public static class Item {
public int topLevelId;
public int secondLevelId;
public int itemId;
public CustomKey customKey;
public Item(int topLevelId, int secondLevelId, int itemId) {
this.topLevelId = topLevelId;
this.secondLevelId = secondLevelId;
this.itemId = itemId;
this.customKey = new CustomKey(topLevelId, secondLevelId);
}
@Override
public String toString() {
return String.format("%d%d%d", this.topLevelId, this.secondLevelId, this.itemId);
}
}
public static class CustomKey {
public int topLevelId;
public int secondLevelId;
public CustomKey(int topLevelId, int secondLevelId) {
this.topLevelId = topLevelId;
this.secondLevelId = secondLevelId;
}
@Override
public String toString() {
return String.format("%d%d", this.topLevelId, this.secondLevelId);
}
}
}
预期的结果是
11
12
21
22
23
24
31
32
但实际结果是
24
31
23
22
12
21
24
31
31
24
12
32
32
11
11
11
31
我认为groupingBy不起作用.
使用CustomKey类有什么问题?
此外,嵌套的映射键正在工作:
Map<Integer, Map<Integer, List<Item>>> entryGrouping =
list.stream()
.collect(Collectors.groupingBy(atta1 -> atta1.topLevelId,
Collectors.groupingBy(atta2 -> atta2.secondLevelId)));
解决方法:
您的CustomKey类不会覆盖Object的equals方法,因此groupingBy认为两个CustomKeys只有在它们是同一个对象时才相等(在您的示例中永远不会这样,因为您为每个Item创建了一个新的CustomKey实例).
public static class CustomKey {
...
@Override
public int hashCode ()
{
// if you override equals, you should also override hashCode
}
@Override
public boolean equals (Object other)
{
if (other == this)
return true;
if (!(other instanceof CustomKey))
return false;
CustomKey okey = (CustomKey) other;
return this.topLevelId == okey.topLevelId && this.secondLevelId == okey.secondLevelId;
}
...
}
内容总结
以上是互联网集市为您收集整理的java – Collectors.groupingBy由两列不起作用全部内容,希望文章能够帮你解决java – Collectors.groupingBy由两列不起作用所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。