Map集合的遍历
a) 键找值
i. 获取所有键
ii. 遍历键的集合,得到每一个键的值
b) 键值对对象找值和键
i. 遍历所有的键值对对象的集合
ii. 根据键值对对象获取键和值
实例:
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String, Object> hm=new HashMap<String,String>();
hm.put("1", "Hello");
hm.put("2", "World");
hm.put("3", "see");
hm.put("4", "Java");
//键找值遍历
Set<String> set1=hm.keySet();
for(String key:set1) {
String value=hm.get(key);
System.out.println(key+"--"+value);
}
System.out.println("----------------------------");
//键值对象找键和值遍历
Set<Map.Entry<String, String>> set2=hm.entrySet();
for(Map.Entry<String, String> me:set2) {
System.out.println(me.getKey()+"--"+me.getValue());
}
// 遍历获取相关对象集合
set1= headMap.entrySet().stream().map(o -> {
return o.getKey().equals("value匹配值") ? o.getValue().toString() : null;
}).collect(Collectors.toList());
// 获取对象
List<Student> students = new ArrayList<>();
students.add(new Student(1,"张三",90));
students.add(new Student(2,"李四",60));
students.add(new Student(3,"王五",30));
students.add(new Student(4,"赵六",85));
int studentId = 3;
Student student = students.stream().filter(o -> o.getId() == studentId).findAny().orElse(null);
}
}
public class Student {
private int id;
private String name;
private int score;
...
}