AdBlock Detected

It looks like you're using an ad-blocker!

Our team work realy hard to produce quality content on this website and we noticed you have ad-blocking enabled. Advertisements and advertising enable us to continue working and provide high-quality content.

Java Stream Map

In this new article about Java Stream Map with examples, we will see some examples of how we can work using Java Streams Map in a functional way.

What is a Java Stream?

We could define a Java Stream as a sequence of objects that support various methods to produce the desired result.

A Stream is a sequence of objects that supports various methods that can be pipelined to produce the desired result.

Given the above definition, we could say that any collection could behave like a sequence, but what about Maps? since they are not sequences. Let’s see how to set up a Map:

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

Let’s get a Collection of the map values:

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

Or we can also get the keys:

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

As we just saw, we obtained a sequence from the values and keys of a map. Now let’s see how we can get a Stream from the previous results:

Stream<String> valuesStream = values.stream();
Stream<String> keysStream = keySet.stream();

And that’s how easy it is to convert it to a Stream.

Working with Maps using Streams

Map to other structures with Stream

Something that often happens quite frequently is wanting to obtain a list of the values of a Map that meet a certain condition, let’s see an example of this.

For this example, we will store names and ages in a Map:

Map<String, Integer> map = new HashMap<>();
map.put("Pepe",5);
map.put("Fran", 8);
map.put("Jose", 7);

List<String> biggerThanSix = map.entrySet().stream()
  .filter(e -> 6 < e.getValue())
  .map(Map.Entry::getKey)
  .collect(Collectors.toList())

The previous lines, we obtained a list from the map, where the condition is all those values that are greater than six, so the answer would be: Fran and Jose.

In this other example, we will see how to get a single value.

Map<String, Integer> map = new HashMap<>();
map.put("Pepe",5);
map.put("Fran", 8);
map.put("Jose", 7);

Optional<String> biggerThanSix = map.entrySet().stream()
  .filter(e -> 7< e.getValue())
  .map(Map.Entry::getKey)
  .findFirst();

In the previous exercise, what we have done is to obtain the first value that meets the condition that is greater than 7, in this case, it would return an Optional with a String with the value Fran.

Stream to Map

Many times we can have a list of objects that meet a pattern, and we want to convert it to a Map. Let’s see an example:

@Getter
@Builder
Public class car() {
  
  private String model;
  private int units;

}

From the above object, we are going to generate a list of Car. And convert it into a map:

public class TestListMap {

    public static void main(String[] args) {
          List<Car> cars = new ArrayList<>();
          Car car1 = Car.build()
            .model("Mazda")
            .units(5)
            .builder();
          Car car2 = Car.build()
            .model("Seat")
            .units(5)
            .builder();
          cars.add(car1);
          cars.add(car2);

          Map<String, Integer> carsMap = cars.stream().collect(
                Collectors.toMap(Car::getModel, Car::getUnits));
          System.out.println("carsMap: " + carsMap);
}

OUTPUT:

carsMap : {Mazda=5, 2=linode.com, Seat=5}

Conclusion

The objective of the article “Java Stream Map with examples” was to demonstrate how it is possible, through the use of Streams in Java, to convert Maps and vice versa. Of course, there are countless other possibilities that you can try out.

Other articles that may interest you

Use of ArrayList in Java

Java Stream Filter with examples

Main HashMap methods in Java

If you need more information, you can leave us a comment or send an email to refactorizando.web@gmail.com You can also contact us through our social media channels on Facebook or twitter and we will be happy to assist you!!

Leave a Reply

Your email address will not be published. Required fields are marked *