我想使用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)));
答案 0 :(得分:5)
您的 public void gatherResults(View view){
// Perform action on click
switch(view.getId()) {
case R.id.button_id_one:
//DO what you want for specific id button_id_one
break;
case R.id.button_id_two:
//DO what you want specific id button_id_two
break;
}
}
课程并未覆盖CustomKey
的{{1}}方法,因此Object
认为两个equals
相等只有当它们是同一个对象时(在您的示例中永远不会出现这种情况,因为您为每个groupingBy
创建了一个新的CustomKey
实例)。
CustomKey