Converting Map<String, pod> to Map<String, String> using Stream API

This example showcases how to transform a Map<String, pod> into a Map<String, String> using Java Stream API.

Original Map:

Map<String, pod> podMap = podAndPool.stream()
                .collect(Collectors.toMap(pod::getResourceId, Function.identity()));

Conversion using Stream API:

Map<String, String> podMap = podAndPool.stream()
                .collect(Collectors.toMap(pod::getResourceId, pod -> pod.getPool().getId()));

Explanation:

  • We utilize the stream() method to create a stream from the original podAndPool map.
  • The collect(Collectors.toMap(...)) method is used to gather the stream elements into a new map.
  • pod::getResourceId provides the key for each entry in the new map, which is the resourceId of the pod object.
  • pod -> pod.getPool().getId() is a lambda expression that extracts the id from the pool object associated with each pod and uses it as the value for the corresponding key in the new map.

By using the Stream API, we achieve the desired conversion efficiently and concisely, providing a readable and maintainable solution.


原文地址: https://www.cveoy.top/t/topic/oBL1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录