我有一个 int 数组列表。我想按唯一数组对其进行分组。
int[] array1 = new int[]{1, 2, 3};
int[] array2 = new int[]{1, 2, 3}; //array1 = array2
int[] array3 = new int[]{0, 2, 3};
List<int[]> test = new ArrayList<>();
test.add(array1);
test.add(array2);
test.add(array3);
test.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
不幸的是,它不起作用。它分组就像任何数组都是唯一的:
{1, 2, 3} - 1
{1, 2, 3} - 1
{0, 2, 3} - 1
我希望:
{1, 2, 3} - 2
{0, 2, 3} - 1
我能做什么?
It groups as if any array was unique:
确实如此。
无论以何种方式实现,您确实会遇到一些困难:内置 Collector
如groupingBy()
和 toMap()
或循环,因为具有相同内容的两个数组在 equals()
方面不相等(还有 hashCode()
)。
您应该考虑使用 List<Integer>
对于这个用例而不是 int[]
.
例如:
public static void main(String[] args) {
int[] array1 = new int[] { 1, 2, 3 };
int[] array2 = new int[] { 1, 2, 3 }; // array1 = array2
int[] array3 = new int[] { 0, 2, 3 };
List<List<Integer>> test = new ArrayList<>();
test.add(Arrays.stream(array1)
.boxed()
.collect(Collectors.toList()));
test.add(Arrays.stream(array2)
.boxed()
.collect(Collectors.toList()));
test.add(Arrays.stream(array3)
.boxed()
.collect(Collectors.toList()));
Map<List<Integer>, Long> map = test.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(map);
}
输出:
{[0, 2, 3]=1, [1, 2, 3]=2}