[英]Using hash maps to create a table in Java
I'm trying to create a program that lets you put any data into a table and you can perform functions like count how many words there are in a column, row etc. Is using a HashMap
the best way to go about this? 我正在尝试创建一个程序,允许您将任何数据放入表中,并且您可以执行函数,例如计算列,行中有多少单词等。使用
HashMap
是最好的方法吗?
If not what can you recommend? 如果没有,你能推荐什么?
At the moment I'm struggling to count each of the letters and it's adding 1 to each of the values each time giving a = 8
, b
and c = 0
目前我正在努力计算每个字母,并且每次给出
a = 8
, b
和c = 0
时每个值都加1
public void main(String[] args){
map.put("0", "a");
map.put("1", "b");
map.put("2", "c");
map.put("3", "a");
map.put("4", "b");
map.put("5", "a");
map.put("6", "b");
map.put("7", "c");
for(Map.Entry ent : map.entrySet()){
if(map.containsValue("a")){
x++;}
else if(map.containsValue("b")){
y++;}
else if(map.containsValue("c")){
z++;}
}
System.out.println("a = " + x);
System.out.println("b = " + y);
System.out.println("c = " + z);
Is using a HashMap the best way to go about this?
使用HashMap是最好的方法吗?
HashMap is a good way to go, but the way you are using it in your example is flawed because you can't simply count how many occurrences of a key are present. HashMap是一个很好的方法,但你在你的例子中使用它的方式是有缺陷的,因为你不能简单地计算一个键的出现次数。
So I suggest using HashMap<String, List<Integer>>
, with List<Integer>
keeping track of row indices: 所以我建议使用
HashMap<String, List<Integer>>
,使用List<Integer>
跟踪行索引:
HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
String[] strs = {"a", "b", "c", "a", "b", "a", "b", "c"};
for(int i = 0 ; i < strs.length ; i++) {
String s = strs[i];
if(map.containsKey(s)) {
map.get(s).add(i);
} else {
map.put(s, Arrays.asList(new Integer[]{i}));
}
}
System.out.println("a = " + map.get("a").size());
System.out.println("b = " + map.get("b").size());
System.out.println("c = " + map.get("c").size());
In case you are okay with using a data structure from a third party, you may want to use Guava's ArrayListMultimap : 如果你可以使用第三方的数据结构,你可能想要使用Guava的ArrayListMultimap :
Multimap<Character, Integer> map = ArrayListMultimap.create();
String str = "abcababc";
for (int i = 0 ; i < str.length() ; i++) {
map.put(str.charAt(i), i);
}
for (Character c : map.keySet()) {
System.out.println(String.format(%c = %d", c, map.get(c).size());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.