黑马程序员技术交流社区
标题:
集合遍历 键找值
[打印本页]
作者:
773809810
时间:
2015-11-3 15:59
标题:
集合遍历 键找值
1),先获取键的集合,然后根据键找值;
(2),先获取每一个键值对,在获取每一个键和值
public class Test{
public static void main(String[] args) {
//创建集合对象
HashMap map=new HashMap();
//创建元素对象
Person p1=new Person("梁朝伟",53);
Person p2=new Person("刘德华",54);
Person p3=new Person("汤镇业",56);
Person p4=new Person("苗侨伟",47);
Person p5=new Person("黄日华",53);
//将元素添加到集合当中
map.put(p1, "无线");
map.put(p2, "有线");
map.put(p3, "刘备");
map.put(p4, "关羽");
map.put(p5, "无线");
//通过获取键的集合,遍历见得集合,通过键找值
Set set = map.keySet();
for(Person key:set){
String value=map.get(key);
System.out.println(key+":"+value); }
System.out.println("===============================");
//通过键值对一一获取键和值
Set> entrySet = map.entrySet();
for (Entry entry : entrySet) {
Person key=entry.getKey();
String value=entry.getValue();
System.out.println(key+":"+value);
}
}
}
//创建元素类
class Person{
private String name;
private int age;
public Person() { }
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
return this.name+":"+this.age;
}
}
作者:
洛克先生EN
时间:
2015-11-3 18:08
这样是不是有些麻烦了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2