如何在hashmap中获取具有相同值的键集

如何在hashmap中获取具有相同值的键集

本文介绍了Java:如何在hashmap中获取具有相同值的键集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个hashmap如下:

1-> x

y

p>

x



z



现在我想知道所有值为x的键(ans:[1,3])。最好的办法是什么?



暴力方法是迭代map并将所有键存储到数组中,其值为x。



有没有任何有效的方法。



谢谢

解决方案

您可以使用可轻松获取所有这些重复值。

  Map< Integer,String> map = new HashMap< Integer,String>(); 
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(原始地图:+地图);

Multimap< String,Integer> multiMap = HashMultimap.create(); (Entry< Integer,String> entry:map.entrySet()){
multiMap.put(entry.getValue(),entry.getKey());
}
System.out.println(); (Entry< String,Collection< Integer>> entry:multiMap.asMap()。entrySet()){
System.out.println(Original value:+ entry .getKey()+映射到键:
+ entry.getValue());

$ / code>

打印出来:

 原始地图:{1 = x,2 = z,3 = x,4 = y,5 = z,6 = x,7 = y} 

原始值:z被映射到键:[2,5]
原始值:y被映射到键:[4,7]
原始值:x被映射到键:[1,3 ,6]

Per @ noahz 的建议 forMap invertFrom 占用较少的行,但可以说更加复杂:

  HashMultimap< String,Integer> multiMap = 
Multimaps.invertFrom(Multimaps.forMap(map),
HashMultimap。< String,Integer> create());

取代:

  Multimap< String,Integer> multiMap = HashMultimap.create(); (Entry< Integer,String> entry:map.entrySet()){
multiMap.put(entry.getValue(),entry.getKey());
}


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<Integer, String> map = new HashMap<Integer, String>();
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<String, Integer> multiMap = HashMultimap.create();
for (Entry<Integer, String> entry : map.entrySet()) {
  multiMap.put(entry.getValue(), entry.getKey());
}
System.out.println();

for (Entry<String, Collection<Integer>> 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<String, Integer> multiMap =
    Multimaps.invertFrom(Multimaps.forMap(map),
        HashMultimap.<String, Integer> create());

in place of:

Multimap<String, Integer> multiMap = HashMultimap.create();
for (Entry<Integer, String> entry : map.entrySet()) {
  multiMap.put(entry.getValue(), entry.getKey());
}

这篇关于Java:如何在hashmap中获取具有相同值的键集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:53