HashMap基础操作

43 阅读1分钟

创建基础待操作数据:

HashMap<Integer,String> obj = new HashMap<>();
obj.put(1,"first");
obj.put(2,"second");
obj.put(3,"three");
obj.put(4,"four");

新增数据

通过三个put接口。具体使用:<java HashMap添加数据>

将HashMap的Values或者keys变成List<T>

通过java8的stream实现。具体的实现如下:(jdk 1.8.0)

// 将HashMap的Values或者keys变成List<T>
List<String> vs = obj.values().stream().collect(Collectors.toList());
System.out.println(vs); // [first, second, three, four]

List<Integer> ks = obj.keySet().stream().collect(Collectors.toList());
System.out.println(ks); // [1, 2, 3, 4]

遍历

obj.forEach((k,v)->System.out.print(k+"_"+v+" ")); 
//输出: 1_first 2_second 3_three 4_four