java里的右面两列没有了_java – Collectors.groupingBy由两列不起作用

我想使用Collectors.groupingBy将两列分组.

我写了以下内容:

public class TestGroupKey

{

public static void main(String... args) {

List 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> 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>> 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,java-8,java-stream,grouping

来源: https://codeday.me/bug/20190828/1754445.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值