java.util.Map遍历(keySet和entrySet方式)

2021/4/9 14:27:06

本文主要是介绍java.util.Map遍历(keySet和entrySet方式),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

@Test

    public void test7(){

        Map<Integer,String> map = new HashMap<Integer,String>();

        map.put(100,"jack");

        map.put(200,"marry");

        map.put(300,"sisi");

        //将Map集合转换成Set集合,并Set集合中存放Map的key值

        Set<Integer> set = map.keySet();

        Iterator<Integer> it = set.iterator();

        while(it.hasNext()){

            Integer key = it.next();//键

            String value = map.get(key);//值

            System.out.println(key+"<->"+value);

        }

    }

    @Test

    public void test8(){

        Map<Integer,String> map = new HashMap<Integer,String>();

        map.put(100,"jack");

        map.put(200,"marry");

        map.put(300,"sisi");

        Set<Entry<Integer,String>> set = map.entrySet();

        for(Entry<Integer,String> entry : set){

            System.out.print(entry.getKey() + "<->");

            System.out.println(entry.getValue());

        }

    }

 

通过测试发现,第二种方式的性能通常要比第一种方式高一倍.

原因:

    keySet()会生成KeyIterator迭代器,其next方法只返回其key值. 

    entrySet()方法会生成EntryIterator 迭代器,其next方法返回一个Entry对象的一个实例,其中包含key和value. 

    二者在此时的性能应该是相同的,但方式一再取得key所对应的value时,此时还要访问Map的这个方法,这时,方式一多遍历了一次table.



这篇关于java.util.Map遍历(keySet和entrySet方式)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程