Sometimes conversions between data structures might become repetitive or prone to errors. If you are working with streams in Java, you might need to grab a list, convert it to a stream, and map it to another data structure.

There is a very easy way to do these types of conversions thanks to the Stream and Collectors APIs from Java. In this article, I’ll be going over different ways in which you can convert streams to other data structures.

I’ll be using as an example a class called Car, which has properties of id: inttype: String and numberOfSeats: int. For all the examples I’ll be using the following two objects.


List

This is the simplest use case where you might just need to convert a stream into a list. For this, you will need to pass in Collectors.toList() to the .collect method.

List<Car> cars = Stream
	    .of(car1, car2)
	    .collect(Collectors.toList());

Map

For you to convert a stream to a map, you will need to call the collect method and pass in as an argument Collectors.toMap. The toMap method accepts two arguments.

The first one will be a lambda that returns the key of the map, the second argument will be a lambda with the value for that key in the map.

Map<Integer, Car> carsMap = Stream
	    .of(car1, car2)
	    .collect(Collectors.toMap(car -> car.id, car -> car));

An important note is that if you end up having more than one element with the same key, this will throw an IllegalStateException saying that there’s a duplicate key.

Stay tuned! I’ll be covering in the next section how to go around this issue.

#programming #java #stream #software-engineering #data-structures #api

Java Stream API — Learn How to Convert Streams to Other Data Structures
2.35 GEEK