Ale*_*ndr 6 java java-8 java-stream
我有一个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()));
Run Code Online (Sandbox Code Playgroud)
不幸的是,它不起作用.它分组就好像任何数组都是唯一的:
{1, 2, 3} - 1
{1, 2, 3} - 1
{0, 2, 3} - 1
Run Code Online (Sandbox Code Playgroud)
我预计:
{1, 2, 3} - 2
{0, 2, 3} - 1
Run Code Online (Sandbox Code Playgroud)
我能做什么?
它分组,就好像任何数组是唯一的一样:
事实就是如此。无论如何,您确实会遇到一些困难来实现它:内置Collectors ,例如groupingBy()andtoMap()或 loop 作为具有相同内容的两个数组在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);
}
Run Code Online (Sandbox Code Playgroud)
输出 :
{[0, 2, 3]=1, [1, 2, 3]=2}
| 归档时间: |
|
| 查看次数: |
1105 次 |
| 最近记录: |