使用四中方式将map中的value存入list中
@Test
public void transMapToList(){
List<String> list1=new ArrayList<>();
List<String> list2=new ArrayList<>();
List<String> list3=new ArrayList<>();
List<String> list4=new ArrayList<>();
Map<String, String> map=new HashMap<>();
map.put("2", "jj");
map.put("3", "uu");
//方式一
long time1=System.nanoTime();
Set<String> set=map.keySet();
Iterator<String> it=set.iterator();
while(it.hasNext()) {
list1.add(map.get(it.next()));
}
long time2=System.nanoTime();
//方式二
Set<Entry<String, String>> it2=map.entrySet();
Iterator<Entry<String, String>> entrys=it2.iterator();
while(entrys.hasNext()) {
Entry<String, String> entry=entrys.next();
list2.add(entry.getValue());
}
long time3=System.nanoTime();
//方式三
map.forEach((key,value)->{
list3.add(value);
});
long time4=System.nanoTime();
//方式四
Collection<String> collection=map.values();
Iterator<String> it4=collection.iterator();
while(it4.hasNext()) {
list4.add(it4.next());
}
long time5=System.nanoTime();
System.out.println("keySet方法耗费时间:"+(time2-time1));
System.out.println("entrySet方法耗费时间:"+(time3-time2));
System.out.println("JDK8 map.forEach耗时:"+(time4-time3));
System.out.println("map.values()耗时:"+(time5-time4));
}
输出结果为:
keySet方法耗费时间:342394
entrySet方法耗费时间:293128
JDK8 map.forEach耗时:1410220
map.values()耗时:410544