How to use stream in Java 8’s map

How to use stream in Java 8's map

brief introduction

Map is a very common collection type in Java. We usually need to traverse the map to obtain some values. Java 8 introduces the concept of stream, so how can we use stream in map?

Basic concepts

Map has key and value, and an entry representing the whole of key and value.

Create a map:

Map<String,String> someMap = new HashMap<>();

Get entryset of map:

Set<Map.Entry<String,String>> entries = someMap.entrySet();

Get the key of the map:

Set<String> keySet = someMap.keySet();

Get the value of the map:

Collection<String> values = someMap.values();

We can see that there are several sets: map, set and collection.

Except that map has no stream, the other two have stream methods:

Stream<Map.Entry<String,String>> entriesStream = entries.stream();
        Stream<String> valuesStream = values.stream();
        Stream<String> keysStream = keySet.stream();

We can traverse the map through several other streams.

Use stream to get the key of map

Let's add a few values to the map first:

someMap.put("jack","20");
someMap.put("bill","35");

We added the name and age fields above.

If we want to find the key with age = 20, we can do this:

Optional<String> optionalName = someMap.entrySet().stream()
                .filter(e -> "20".equals(e.getValue()))
                .map(Map.Entry::getKey)
                .findFirst();

        log.info(optionalName.get());

Because the returned value is optional, if the value does not exist, we can also process:

optionalName = someMap.entrySet().stream()
                .filter(e -> "Non ages".equals(e.getValue()))
                .map(Map.Entry::getKey).findFirst();

        log.info("{}",optionalName.isPresent());

In the above example, we call ispresent to determine whether age exists.

If there are multiple values, we can write:

someMap.put("alice","20");
        List<String> listnames = someMap.entrySet().stream()
                .filter(e -> e.getValue().equals("20"))
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        log.info("{}",listnames);

Above, we called collect (collectors. Tolist()) to convert the value into a list.

Use stream to get the value of the map

We can get the key of the map above. Similarly, we can also get the value of the map:

List<String> listAges = someMap.entrySet().stream()
                .filter(e -> e.getKey().equals("alice"))
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());

        log.info("{}",listAges);

Above, we matched that the key value is the value of Alice.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>