gpt4 book ai didi

java - 如何在hashmap中找到value的key

转载 作者:行者123 更新时间:2023-12-02 05:08:50 30 4
gpt4 key购买 nike

我想根据 HashMap 中的特定值获取键

在下面的程序中,我尝试找到句子中单词的最大长度。我使用 HashMap 将单词存储为键,将单词的长度存储为值。

我尝试这个代码:

import java.util.*;
public class Test3 {


public static void main(String[] args) {
HashMap<String, Integer> map=new HashMap<String, Integer>();
String sent="EGInnovations located in seven countries in the world";
String[] words=sent.split(" ");
int len=0;
int max=0;
int min=0;
int temp=0;
for(String word : words)
{

len=word.length();
map.put(word, len);
}

Iterator it=map.entrySet().iterator();
while(it.hasNext())
{
Map.Entry str=(Map.Entry)it.next();
System.out.println(str.getKey()+" "+str.getValue());

max=(Integer)str.getValue();
if(max>min)
{
temp=max;
min=max;
}
}
System.out.println(temp);
System.out.println(map.get(temp));
}

}

我得到了这个输出:

seven 5
located 7
world 5
EGInnovations 13
the 3
countries 9
in 2

13 //here I got the maximum length
null //But If I try to get the key of the value(13) It will give "null".

请帮助解决方案或给我想法来获取特定值的 key ...

最佳答案

您可以创建一个新的 Map,将长度存储为键,将值列表存储为映射中的值。

因此,每当您传递一个长度时,您都可以获得具有该长度的值。

下面的程序为您提供了一个映射(以及重复的值,例如出现两次的“in”),可用于获取长度的最大和最小值及其值。

public static void main(String[] args) {
HashMap<Integer, List<String>> map = new HashMap<Integer, List<String>>();
String sent = "EGInnovations located in seven countries in the world";
String[] words = sent.split(" ");
int len = 0;
List<String> stringList;
for (String word : words) {
len = word.length();

stringList = map.get(len);
if (stringList == null) {
stringList = new ArrayList<String>();
map.put(len, stringList);
}
stringList.add(word);
}

if (!map.isEmpty()) {
System.out.println("Full length map : \n" + map); //Printing full length map
System.out.println();
List<Integer> lengthList = new ArrayList<Integer>(map.keySet());

System.out.println("Minimum Length : " + Collections.min(lengthList));
System.out.println("Minimum Length Words : " + map.get(Collections.min(lengthList)));

System.out.println("\nMax Length : " + Collections.max(lengthList));
System.out.println("Max Length Words : " + map.get(Collections.max(lengthList)));
}
}

更新:

对于您的代码,您可以在while 循环之后添加以下代码。

//temp contains max length value

it = map.entrySet().iterator();
System.out.println("Max length : " + temp);
while(it.hasNext()) {
Map.Entry str=(Map.Entry)it.next();

if (str.getValue().equals(temp)) {
System.out.println("Word : " + str.getKey());
}
}

关于java - 如何在hashmap中找到value的key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27518493/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com