package com.li.springboot.text;
import java.util.*;
@SuppressWarnings({"all"})
public class Text {
public static void main(String[] args) {
HashMap<String, Dog> hashMap = new HashMap<String, Dog>();
hashMap.put("num1", new Dog("大黄", 2));
hashMap.put("num2", new Dog("小黄", 2));
hashMap.put("num3", new Dog("乐乐", 3));
//KeySet()
System.out.println("---------------KeySet()------------------");
Set<String> strings = hashMap.keySet();
System.out.println("======迭代器======");
//迭代器
Iterator iterator = strings.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println(next + "_" + hashMap.get(next));
}
//增强for
System.out.println("======增强for======");
for (String o : strings) {
System.out.println(o + "_" + hashMap.get(o));
}
System.out.println("---------------values()------------------");
//values()
Collection values = hashMap.values();
//迭代器
System.out.println("======迭代器======");
Iterator iterator1 = values.iterator();
while (iterator1.hasNext()) {
Object next = iterator1.next();
System.out.println(next);
}
//增强for
System.out.println("======增强for======");
for (Object o : values) {
System.out.println(o);
}
//entrySet()
System.out.println("---------------entrySet()------------------");
Set entrySet = hashMap.entrySet();
for (Object o : entrySet) {
Map.Entry entry = (Map.Entry) o;
System.out.println(entry.getKey() + "_" + entry.getValue());
}
}
}
class Dog {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
HashMap 集合遍历方式(三种)
最新推荐文章于 2024-08-30 18:40:43 发布