Six traversal methods of Java Map

Initialize a Map and store data in the Map

        Map map = new HashMap();
        map.put("1","美女");
        map.put("2","帅哥");
        map.put("说唱","rapper");
        map.put("流行","歌手");
        map.put(null,"小刘");
        map.put("小张",null);
        map.put("小李","小红");

=================================================

The first way to enhance the for loop (take the key of the Map)

First take out all the keys of the map, and take out the corresponding value through the key

        Set keyset = map.keySet();
        for (Object key : keyset) {
            System.out.println(key + "-" + map.get(key));
        }

output result

 ================================================

The second way is to traverse the iterator (take the key of the Map)

First take out all the keys of the map, and take out the corresponding value through the key

Get the iterator of the keyset

The method hasNext() judges whether there is data in the next iterator

The method next() takes the next data pointed to by iterator

        Set keyset = map.keySet();
        Iterator iterator = keyset.iterator();
        while(iterator.hasNext()){
            Object key = iterator.next();
            System.out.println(key + "-" + map.get(key));
        }

output result

=================================================

The third way to enhance the for loop (take the value of Map)

First take out all the values ​​​​of the map

        Collection values = map.values();
        for(Object value : values){
            System.out.println(value);
        }

output result

=================================================

The fourth way iterator traversal (take the value of Map)

First take out all the values ​​​​of the map

        Collection values = map.values();
        Iterator iterator = values.iterator();
        while(iterator.hasNext()){
            Object value = iterator.next();
            System.out.println(value);
        }

 output result

 

=================================================

The fifth way to enhance the for loop (take the entry of Map)

Get kv through EntrySet

        Set entrySet = map.entrySet();
        for(Object entry : entrySet){
            Map.Entry m = (Map.Entry) entry;
            System.out.println(m.getKey() + "-" + m.getValue());
        }

 output result

=================================================

The sixth way is iterator traversal (take the entry of Map)

When the entry is just obtained, the object type is Object

Downcasting is required to convert the object type to Map.Entry

        Set entrySet = map.entrySet();
        Iterator iterator = entrySet.iterator();
        while(iterator.hasNext()){
            Object entry = iterator.next();
            Map.Entry m= (Map.Entry) entry;
            System.out.println(m.getKey() + "-" + m.getValue());
        }

output result 

Guess you like

Origin blog.csdn.net/henry594xiaoli/article/details/127215421