栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java反转图

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java反转图

映射中的值可能不是唯一的。但是,如果它们是(在您的情况下),则可以按照您在问题中所写的内容进行操作,并创建将其转换的通用方法:

private static <V, K> Map<V, K> invert(Map<K, V> map) {    Map<V, K> inv = new HashMap<V, K>();    for (Entry<K, V> entry : map.entrySet())        inv.put(entry.getValue(), entry.getKey());    return inv;}

Java 8:

public static <V, K> Map<V, K> invert(Map<K, V> map) {    return map.entrySet()   .stream()   .collect(Collectors.toMap(Entry::getValue, Entry::getKey));}

用法示例:

public static void main(String[] args) {    Map<String, Integer> map = new HashMap<String, Integer>();    map.put("Hello", 0);    map.put("World!", 1);    Map<Integer, String> inv = invert(map);    System.out.println(inv); // outputs something like "{0=Hello, 1=World!}"}

旁注:该

put(.., ..)
方法将返回键的“旧”值。如果它不为null,则可能抛出
new IllegalArgumentException("Mapvalues must be unique")
或类似的东西。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/449828.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号