简体   繁体   中英

Finding duplicates in a 2D array

Lets say I have a 2D array with values called int map[][] = new int[10][10] . The default values in the array are 0 's and some values in map[][] can change to -1 , -2 , -3 , etc.

Let's say the values in the 2D array are changing constantly and I want to my program to perform something when there are for example, 3 of -3 's found or if 2 of -2 's found, etc.

I have no idea how to implement this. Please can someone help?

You need to build a frequency map for the input 2D array, by iterating the array and adding to the map the values which are not equal to 0.

It is convenient to use Stream API for this, where the input array is converted into a IntStream of int numbers, which is filtered and the frequencies are counted for non-zero numbers.

When the frequency map is ready, the values which occur only once may be excluded.

static Map<Integer, Integer> calculateFrequency(int[][] arr) {
    return Arrays
        .stream(arr) // Stream<int[]>
        .flatMapToInt(a -> Arrays.stream(a)) // IntStream
        .boxed() // Stream<Integer>
        .filter(x -> x != 0) // do not count 0
        .collect(Collectors.groupingBy(x -> x, Collectors.summingInt(x -> 1))); // build the map
}

static Map<Integer, Integer> removeSingles(Map<Integer, Integer> frequencyMap) {
    return frequencyMap
        .entrySet()
        .stream() // Stream<Map.Entry<Integer, Integer>>
        .filter(x -> x.getValue() > 1) // do not count single
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); // build the map
}


// test
int[][] arr = new int[10][10];
arr[0][1] = -1;
arr[3][2] = -1;
arr[7][7] = -1;
arr[1][2] = -2;
arr[8][5] = -3;
    
Map<Integer, Integer> frequencyMap = calculateFrequency(arr);
System.out.println("frequencyMap: " + frequencyMap);
    
System.out.println("without singles: " + removeSingles(frequencyMap));

output:

frequencyMap: {-1=3, -2=2, -3=1}
without singles: {-1=3, -2=2}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM