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

Posted 柒弦宇轩

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java遍历List中的map的几种方法相关的知识,希望对你有一定的参考价值。

 Student 类

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( "\\u5f20\\u4e09", 26, 180 );
		Student stu2 = new Student( "\\u674e\\u56db", 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的几种方法的主要内容,如果未能解决你的问题,请参考以下文章

Java之List和Map的几种遍历方式

java 中遍历Map的几种方法

谈谈java中遍历Map的几种方法

谈谈java中遍历Map的几种方法

遍历Map的几种方式

java Map 怎么遍历