Map常用场景
# map来track每个元素的index Map <item, index> map = new HashMap<>(); # map来track每个元素出现的频率 Map <item, freq> map = new HashMap<>(); # char字符在ASCII中都有对应,故可简化 int[]map = new int[256]; # map来group一串同类 Map<String, List<String>> map = new HashMap<>();
Map常用操作
map.containsKey(k) map.put(k,v) map.get(k) map.remove(k) map.size() map.isEmpty() map.clear()
遍历map
// map.entrySet() for (Map.Entry<Integer, Integer> entry : map.entrySet()) { System.out.print( entry.getKey() + "," + entry.getValue()); } // map.keySet() for (String name : map.keySet()) { System.out.println("key: " + name); } // map.values() for (String url : map.values()) { System.out.println("value: " + url); }
将给定String[]inputStrings中的每个元素加到Map<String, List<String>> 里
简洁版
for(String s : inputStrings) { List<String> list = map.getOrDefault(s, new ArrayList<>()); list.add(s); map.put(s, list); }
将map.values()里的每一组List<String>list 转到返回的List<List<String>>中
List<List<String>> result = new ArrayList<>(); for (List<String> list : map.values()) { result.add(list); } return result;
简洁版
return new ArrayList<>(map.values());