Java Hashmap how to handle key collision for grid of words

喜你入骨 提交于 2020-01-15 10:23:27

问题


I have grid of words of 100*100 dimensions, this means characters repeat themselves, I want to put my grid of words into a hashmap for faster searching. When the key (character) isn't in the hashmap, I add it in to the hashmap as key and the value is the line and column (the position) of the character in the grid, but now how can I handle when there's multiple characters? For example, "a" is already in the hashmap, but there's another "a" in a different line and column position) in the grid, I want to add it also, how can I accomplish this for best performance? I absolutely need to use a hashmap


回答1:


The above link provided by Minh provides a good overview.

If you don't want or can't use external apis, you can check the option with collection as value:

//Let's say Pos handle your grid coordinates
class Pos {
    int line, col;
    ...
}
...
// You may define the map as
Map<String, List<Pos>> myGrid = new HashMap<>();
...
// And for a given key and pos - in a loop e.g
String key = ... // e.g "a"
Pos pos = ... // e.g {0, 0}
myGrid.computeIfAbsent(key, k->new ArrayList<>()).add(pos);

You may also use a Set-HashSet instead of List-ArrayList depending on your need.

Cheers!




回答2:


A sample program that is based on Ayo's idea:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class Pos {
    public int x;
    public int y;

    Pos(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class Test {

    public static void main(String[] args) {
        // 2 x 3 array
        char[][] array = { { 'a', 'a', 'e' }, { 'd', 'e', 'f' } };
        Map<Character, List<Pos>> map = new HashMap<>();

        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                map.computeIfAbsent(array[i][j], c -> new ArrayList<>()).add(new Pos(i, j));
            }
        }

        map.forEach((key, value) -> {
            System.out.println("Key: " + key);
            value.stream().forEach(pos -> System.out.printf("(%d, %d) ", pos.x, pos.y));
            System.out.println();
        });
    }
}


来源:https://stackoverflow.com/questions/58653140/java-hashmap-how-to-handle-key-collision-for-grid-of-words

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!