遍历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);
}
}
以上仅供参考,已经测试通过。
- 集合List、Set、Map的遍历方式
- 遍历list、set和map集合的方式
- java中list,set,Map集合的遍历方式
- List、Set集合Map集合的遍历
- Java中Map集合和List集合的遍历方式
- Map、Set、List集合的遍历
- list和set集合的几种遍历方式
- List 、Set 、Map 的遍历方式
- Map集合,List集合,Array数组,Iterator迭代,Collection集合,Set集合的多种遍历方式
- List、Set集合遍历方式
- List、Set集合遍历方式
- List、Set集合遍历方式
- List、Set集合遍历方式
- List、Set集合遍历方式
- List、Set和Map的遍历方法
- list和set集合的遍历
- list和set集合的遍历
- list和set集合的遍历
- C# DataGridView改变行颜色
- 7.Python基础 函数
- eclipse中svn的各种图标详解
- Exception in thread "main" org.hibernate.MappingException: Unknown entity: org.model.Kcb
- C# 进制转换(二进制、十六进制、十进制互转)
- 遍历list、set和map集合的方式
- Edmonds_Karp算法(增广路算法)
- 使用Volley加载网络图片
- 认识Thread.join()
- OgnlContext、OgnlValueStack、CompoundRoot的数据结构
- 概率论与统计学的重要东西
- 常用传感器协议4:CJ/T-188 冷热量表协议解析3
- Windows环境下搭建Cocos2d-x3.2环境并配置android交叉编译环境
- 下载不同版本的hadoop