怎么办map形转换成list
1、创建java类:TestMap2List,
2、编辑java代码,将数据放入map中,
Map<Integer, String> map = new HashMap();
map.put(10, "apple");
map.put(20, "orange");
map.put(30, "banana");
map.put(40, "watermelon");
map.put(50, "dragonfruit");
3、新建ArrayList对象,将Map对象的内容,插入ArrayList中,
Collection<String> valueCollection = map.values();
final int size = valueCollection.size();
List<String> valueList = new ArrayList<String>(valueCollection);
String[] valueArray = new String[size];
map.values().toArray(valueArray);
for (int i=0;i<valueArray.length;i++) {
System.out.println(valueList.get(i));
}
4、加入输出语句,执行java代码,在控制台中输入ArrayList中的结果,
装入list就可以了
可以使用迭代器,示例如下
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class MapOrList {
//map转换成lisy
public static List mapTransitionList(Map map) {
List list = new ArrayList();
Iterator iter = map.entrySet().iterator(); //获得map的Iterator
while(iter.hasNext()) {
Entry entry = (Entry)iter.next();
list.add(entry.getValue());
}
return list;
}
public static void main(String[] args) {
Map map = new HashMap();
map.put("aaa", 11);
map.put("bbb", "22ss");
map.put("ccc", "汉字");
List list = mapTransitionList(map);
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
}
}
广告 您可能关注的内容 |