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
數字并使用方法的最后一部分。雖然這種方法減少了散列時間,但這里有一些假設可能不適用于您的情況。
添加回答
舉報