Home  >  Article  >  Java  >  Introduction to five methods of traversing a map

Introduction to five methods of traversing a map

王林
王林forward
2020-10-13 17:10:273476browse

Introduction to five methods of traversing a map

Map collection traversal is often used in daily development. The differences between several traversal methods are introduced below.

(Recommended tutorial: java course)

1. How to write Iterator entrySet [recommended for JDK8 and below], Map.Entry is the internal interface of the Map interface, and obtains the iterator. Then take out the Map.Entry

        Iterator<Map.Entry<Integer,String>> iterator=map.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<Integer,String> entry=iterator1.next();
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }

2 in each iterator in turn. How to write Iterator keyset [not recommended, you can only get the key, and then get the corresponding value through the key, and repeat the calculation]

        Iterator<Integer> iterator=map.keySet().iterator();
        while (iterator.hasNext()){
            Integer key=iterator.next();
            System.out.println(key);
            System.out.println(map.get(key));
        }

3. Foreach traversal method [Recommended writing method below JDK8]

        for(Map.Entry<Integer,String> entry:map.entrySet()){
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        };

4. Lambda expression traversal [JDK8 recommended writing method, simple]

        map.forEach((key,value)->{
            System.out.println(key);
            System.out.println(value);
        });

5. Stream stream traversal Map [Writing method not recommended under JDK8] , Repeated calculation]

        map.entrySet().stream().forEach((Map.Entry<Integer, String> entry) -> {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        });

If there is some intermediate processing in the Map collection, filtering operations can be performed, and streaming traversal is also very convenient.

Related recommendations: java introductory tutorial

The above is the detailed content of Introduction to five methods of traversing a map. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete