3 回答
TA贡献1789条经验 获得超8个赞
将 包装int[]在实现equalsand的类中hashCode,然后Map将包装类构建为实例计数。
class IntArray {
private int[] array;
public IntArray(int[] array) {
this.array = array;
}
@Override
public int hashCode() {
return Arrays.hashCode(this.array);
}
@Override
public boolean equals(Object obj) {
return (obj instanceof IntArray && Arrays.equals(this.array, ((IntArray) obj).array));
}
@Override
public String toString() {
return Arrays.toString(this.array);
}
}
测试
int[][] input = {{1,2,3},
{1,0,3},
{1,2,3},
{5,2,6},
{5,2,6},
{5,2,6}};
Map<IntArray, Long> map = Arrays.stream(input).map(IntArray::new)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
map.entrySet().forEach(System.out::println);
输出
[1, 2, 3]=2
[1, 0, 3]=1
[5, 2, 6]=3
注意:上述解决方案比Ravindra Ranwala 的解决方案更快并且使用更少的内存,但它确实需要创建一个额外的类,因此哪个更好是有争议的。
对于较小的阵列,请使用下面由 Ravindra Ranwala 提供的更简单的解决方案。
对于较大的阵列,上述解决方案可能更好。
Map<List<Integer>, Long> map = Stream.of(input)
.map(a -> Arrays.stream(a).boxed().collect(Collectors.toList()))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
TA贡献1854条经验 获得超8个赞
你可以这样做,
Map<List<Integer>, Long> result = Stream.of(source)
.map(a -> Arrays.stream(a).boxed().collect(Collectors.toList()))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
这是输出,
{[1, 2, 3]=2, [1, 0, 3]=1, [5, 2, 6]=3}
TA贡献2065条经验 获得超14个赞
如果该数组的所有重复的元素序列彼此相似并且每个数组的长度不多,则可以将每个数组映射到一个int
数字并使用方法的最后一部分。虽然这种方法减少了散列时间,但这里有一些假设可能不适用于您的情况。
添加回答
举报