How to use stream in Java 8 map

Introduction to the

A Map is a very common collection type in Java, and we often need to iterate over a Map to get some value. Java 8 introduced the concept of Stream, so how do we use Stream in a Map?

The basic concept

A Map has keys, values and an Entry that represents the whole of the key and value.

Create a Map:

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

Get entrySet for Map:

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

Get the map key:

Set<String> keySet = someMap.keySet();
Copy the code

Get the map value:

Collection<String> values = someMap.values();
Copy the code

Above we can see that there are several collections: Map, Set, Collection.

Except for Map, which 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();
Copy the code

We can traverse the map through several other streams.

Use Stream to get the map key

Let’s start by adding a few values to map:

someMap.put("jack"."20");
someMap.put("bill"."35");
Copy the code

Above we added the name and age fields.

If we want to find a 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());
Copy the code

Since the value is Optional, we can also do this if the value does not exist:

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

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

In the example above we check whether age exists by calling isPresent.

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);
Copy the code

Collect (Collectors. ToList ()) is called to convert the value to a List.

Get the map value using stream

We can also obtain 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);
Copy the code

So we matched the key that is Alice’s value.

conclusion

Stream is a very powerful feature, and by combining it with Map, we can easily manipulate map objects.

Examples of this article github.com/ddean2009/l…

Welcome to pay attention to my public number: procedures those things, more wonderful waiting for you! For more, visit www.flydean.com