java获取hashmap的key,Java:如何在hashmap中获取具有相同值的键集

本文介绍了一种更有效的方法,通过使用Java的Multimap结构来查找HashMap中值为 'x' 的所有键,避免了遍历整个映射的低效方式。作者展示了如何使用HashMultimap并演示了简洁的代码实现。
摘要由CSDN通过智能技术生成

I have a hashmap as below:

1->x

2->y

3->x

4->z

Now i want to know all keys whose value is x (ans: [1,3] ). what is best way to do?

Brute force way is to just iterate over map and store all keys in array whose value is x.

Is there any efficient way for this.

Thanks

解决方案

You can use a MultiMap to easily get all those duplicate values.

Map map = new HashMap();

map.put(1, "x");

map.put(2, "y");

map.put(2, "z");

map.put(3, "x");

map.put(4, "y");

map.put(5, "z");

map.put(6, "x");

map.put(7, "y");

System.out.println("Original map: " + map);

Multimap multiMap = HashMultimap.create();

for (Entry entry : map.entrySet()) {

multiMap.put(entry.getValue(), entry.getKey());

}

System.out.println();

for (Entry> entry : multiMap.asMap().entrySet()) {

System.out.println("Original value: " + entry.getKey() + " was mapped to keys: "

+ entry.getValue());

}

Prints out:

Original map: {1=x, 2=z, 3=x, 4=y, 5=z, 6=x, 7=y}

Original value: z was mapped to keys: [2, 5]

Original value: y was mapped to keys: [4, 7]

Original value: x was mapped to keys: [1, 3, 6]

Per @noahz's suggestion, forMap and invertFrom takes fewer lines, but is arguably more complex to read:

HashMultimap multiMap =

Multimaps.invertFrom(Multimaps.forMap(map),

HashMultimap. create());

in place of:

Multimap multiMap = HashMultimap.create();

for (Entry entry : map.entrySet()) {

multiMap.put(entry.getValue(), entry.getKey());

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值