Java Stream: Convert Map<String, pod> to Map<String, String> using Stream API
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 originalpodAndPoolmap. - The
collect(Collectors.toMap(...))method is used to gather the stream elements into a new map. pod::getResourceIdprovides the key for each entry in the new map, which is theresourceIdof thepodobject.pod -> pod.getPool().getId()is a lambda expression that extracts theidfrom thepoolobject associated with eachpodand 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 著作权归作者所有。请勿转载和采集!