遍历list、set和map集合的方式

来源:互联网 发布:梦幻西游伤害换算法伤 编辑:程序博客网 时间:2024/06/06 15:04

以下是遍历三种集合的常用方式: 为了大家查看方便,我进行如下分类。

一、新建一个类对象Personpublic class Person{

private Integer id;

private String name;

private Integer age; //提供有参数构造方法和无参数构造方法

public Person(){}

public Person(Integer id, String name, Integer age) {

this.id = id;

this.name = name;

this.age = age;

} //提供get/set方法

}

二、建立集合并且遍历

(1)遍历map集合

@Test

public void testMap(){

Map<Integer,Person> map =new HashMap<Integer,Person>(); //新建一个泛型map

for(int i=0;i<10;i++){  

map.put(i, new Person(i,"zhang",i+1));//将新建的对象放在内存中

}

//遍历map(最常用,也是最好用的,其他的方式本文暂未提出)

for(Map.Entry<Integer, Person> enty:map.entrySet()){

System.out.println("map"+enty.getKey()+"------"+"\t"+enty.getValue());

} }

(2)遍历List集合

@Test

public void testList(){

List list=new ArrayList(); //新建一个常规list

List<Integer> list=new ArrayList<Integer>(); //新建泛型集合list2

for(int j=0;j<10;j++){

list.add(j); //暂时保存在内存中

}

//遍历list,第一种方式 for(int y=0;y<list.size();y++){

System.out.println("list:"+list.get(y));

}

//遍历泛型集合list,第二种使用迭代器,JDK1.5以后才有

for(Integer inh:list2){

System.out.println("泛型list:"+inh);  

} 

}

(3)遍历Set集合

@Test

public void testSet(){

Map<Integer,Person> map =new HashMap<Integer,Person>(); //新建一个泛型map

for(int i=0;i<10;i++){

map.put(i, new Person(i,"zhang",i+1));//将新建的对象放在内存中

}

Set<Person> set =new HashSet<Person>(); //新建set集合

for(Map.Entry<Integer, Person> enty:map.entrySet()){

set.add(enty.getValue());

}

//遍历泛型set集合(最好用,类似List,但Set集合无下表,没有getIndex()方法)

for(Person p:set){

System.out.println("set:"+p);

}

}

以上仅供参考,已经测试通过。

0 0