1,HashMap双列集合,第一列是key,第二列是value,key的类型与set的类型一样,不能重复,而value的类型可以重复,类型则为colloection,如果想获得键(key)的集合,则用keySet,想获得值(value)的集合,则用户values,如果想获得键值对的集合,则用entrySet方法,代码如下
Map<String,String>map=new HashMap<>(); map.put("1","张三"); map.put("2","李四"); map.put("3","王五"); System.out.println(map); Set<String> strings = map.keySet(); System.out.println(strings); Collection<String> values = map.values(); System.out.println(values); Set<Map.Entry<String, String>> entries = map.entrySet(); System.out.println(entries);
结果如下
{1=张三, 2=李四, 3=王五}
[1, 2, 3]
[张三, 李四, 王五]
[1=张三, 2=李四, 3=王五]
2,判断输入的字符串的字母的个数
public class TreeMapTest { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); System.out.println("请输入一串字母"); String str = scanner.next(); TreeMap<Character, Integer> treeMap = new TreeMap<Character, Integer>(); char[] chars = str.toCharArray(); for (char aChar : chars) { Integer value = treeMap.get(aChar); treeMap.put(aChar, value == null ? 1 : value + 1); } System.out.println(treeMap); } }