码迷,mamicode.com
首页 > 编程语言 > 详细

java遍历List中的map的几种方法

时间:2018-12-07 14:59:55      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:key   stringbu   asn   import   app   ++   pen   his   ext   

 Stueng 类

public class Student {
	private String name;
	private int age;
	private int taller;
	
	public Student( String name, int age, int taller ) {
		this.name = name;
		this.age = age;
		this.taller = taller;
	}
	
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("Student [name=").append(name).append(", age=").append(age).append(", taller=").append(taller)
				.append("]");
		return builder.toString();
	}

	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 void setTaller( int taller ) {
		this.taller = taller;
	}
	
	public int getTaller() {
		return taller;
	}
}

 

测试类

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import PubClass.Student;

public class ListAddMap {
	
	public static void main( String args[] ) {
		
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		
		Student stu1 = new Student( "张三", 26, 180 );
		Student stu2 = new Student( "李四", 28, 175 );
		
		map.put( "stu1", stu1 );
		map.put( "stu2", stu2 );
		list.add( map );
		
		System.out.println( "方法一 :" );
        for( int i = 0; i < list.size(); i++ ) {
        	System.out.println( list.get(i) );
        }
        
        System.out.println( "方法二 :" );
        for( Map<String, Object> mapList : list ) {
        	for( String key : mapList.keySet() ) {
        		System.out.println( key + "-->" + mapList.get(key) );
        	}
        }
        
        System.out.println( "方法三 :" );
        for( int i = 0; i < list.size(); i++ ) {
        	Map<String, Object> mapList = list.get(i);
            Iterator<String> it = mapList.keySet().iterator();
            while( it.hasNext() ) {
                String str = (String) it.next();
                System.out.println( "key-->" + str + "\t value-->" + map.get(str) );
            }
        }
	}
	
}

 

运行结果

技术分享图片

 

java遍历List中的map的几种方法

标签:key   stringbu   asn   import   app   ++   pen   his   ext   

原文地址:https://www.cnblogs.com/dgm2088/p/10082327.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!