You can use a list and java8 streams.
Map<List<Integer>, Long> mapList = Stream.of(array1, array2, array3)
.map(Arrays::stream)
.map(IntStream::boxed)
.map(stream -> stream.collect(Collectors.toList()))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
If you want the Map<int[], Long>
you can continue after the collect()
above like.
// ... collect ...
.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey()
.stream().mapToInt(i -> i).toArray(), Entry::getValue));
// returns Map<int[], Long>
Still I think that the question emphasizes the use of arrays. You can create a wrapper class for the int[]
object.
This is just an example for the int array wrapper, even though a more complex class can be used, with something like the factory pattern to allow the use of all array primitives and even array of objects.
public class IntArray {
private final int[] array;
private IntArray(final int[] array) {
this.array = array;
}
public static IntArray wrap(final int[] array) {
return new IntArray(array);
}
public int[] unwrap() {
return array;
}
@Override
public boolean equals(final Object obj) {
return obj instanceof IntArray
&& Arrays.equals(((IntArray) obj).array, array);
}
@Override
public int hashCode() {
return Arrays.hashCode(array);
}
@Override
public String toString() {
return Arrays.toString(array);
}
}
Here the wrap(..)
method is optional, IntArray::new
can be used instead, also the toString()
method is optional to allow the conversion of the internal array to string without the need un unwrap.
The necessary methods are equals(..)
and hashcode()
because they are required for the map to work properly.
Here is more info about it.
Understanding the workings of equals and hashCode in a HashMap
Finally it can be used like.
Map<IntArray, Long> mapArray = Stream.of(array1, array2, array3)
.map(IntArray::wrap)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
And again if you want the array as key of the map (as a Map<int[], Long>
) you can do the following (note that in this case, a new array is not created, it just uses the first unique array that it finds).
// ... collect ...
.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey()
.unwrap(), Entry::getValue));
// returns Map<int[], Long>