Search code examples
javajava-8collect

Java stream - How to go over a list, show elments and collect them in the same line


I have the following:

Map<String, String> carMap;
List<Car> cars = ......

carMap = cars.stream
.collect(Collectors.toMap(key -> key.getValue(), key -> key.getColor()));

I'm iterating over cars and I'd like to show on screen what is included into the map. I could do something like this after collecting the map but I don't want to go over the list again:

cars.stream()
      .forEach(System.out::println)

Is there a way to do a sysout in this line?

carMap = cars.stream
.collect(Collectors.toMap(key -> key.getValue(), key -> key.getColor()));

I tried with a forEach after stream but obviously didn't work


Solution

  • If it's just for debugging purposes and you want to collect as well as print, you can simply use peek here -

    Map<String, String> carMap = cars.stream()
        .peek(c -> System.out.println("Value: " + c.getValue() + " and Color: " + c.getColor()))
        .collect(Collectors.toMap(key -> key.getValue(), key -> key.getColor()));