文字列a 的内容是"ab", "cd", "ab", "efg", "ab", "cd"
分别运用hashmap和treemap对各个元素进行检查,
有相同的与元素的话,打出他的编号
也就是说结果是这样
ab 1
cd 1
ab 2
efg 1
ab 3
cd 2请大家解救 可能的话请附加上说明 谢谢
分别运用hashmap和treemap对各个元素进行检查,
有相同的与元素的话,打出他的编号
也就是说结果是这样
ab 1
cd 1
ab 2
efg 1
ab 3
cd 2请大家解救 可能的话请附加上说明 谢谢
LZ这个用LIST比较好吧
map.put(key, v)
map.get(key)
(Integer) map.get(key)
Map<String,List<String>>要不用类似这样吧,简单点的话,直接用第一个就好
import java.util.HashMap;
import java.util.Map;public class Test { public static void main(String[] args) {
String[] data = {"ab","cd","ab","efg","ab","cd"};
Map<String, Integer> map = new HashMap<String, Integer>();
for(String str : data){
Object obj = map.get(str);
if(null == obj){
System.out.println(str+" 1");
map.put(str, 1);
}else{
int num = (Integer)obj;
System.out.println(str+" "+(num+1));
map.put(str, num+1);
}
}
}
}
public static void main(String[] args) {
String[] array = { "ab", "cd", "ab", "efg", "ab", "cd" };
Map<String, Integer> map = new HashMap<String, Integer>();
for (String key : array) {
if (map.isEmpty() || !map.containsKey(key)) {
System.out.println(key + " " + 1);
map.put(key, 1);
} else {
System.out.println(key + " " + (map.get(key) + 1));
map.put(key, map.get(key) + 1);
}
}
}
String[] data = {"ab","cd","ab","efg","ab","cd"};
Map<String, Integer> map = new HashMap<String, Integer>();
for(String str : data){
Integer key = map.get(str);
key = key == null ? 0 : key;
map.put(str, ++key);
System.out.println(str+key);
}
但不知道为什么要分别用 HashMap 和 TreeMap .