您可以使用方法引用 'Map.Entry::getKey' 在 'Collectors.toMap' 中调用 'getKey' 方法。

import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);

        // 使用方法引用 Map.Entry::getKey 调用 getKey 方法
        Map<String, Integer> result = map.entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println(result);
    }
}

输出结果:

{A=1, B=2, C=3}

在上面的示例中,我们首先创建了一个 'Map' 对象,并向其中添加了一些键值对。然后,我们使用 'map.entrySet().stream()' 将 'Map' 转换为 'Stream<Map.Entry<K, V>>',然后使用 'Collectors.toMap' 将其转换为 'Map' 对象。在 'Collectors.toMap' 中,我们使用方法引用 'Map.Entry::getKey' 调用 'getKey' 方法来作为键。'Map.Entry::getValue' 同样可以用于调用 'getValue' 方法作为值。最后,我们将结果打印出来,得到了原始 'Map' 的副本。

Java Collectors.toMap 使用方法引用获取 Map.Entry 键值

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

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