问题
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