[英]Getting key by value in LinkedHashMap using Java
I have a big LinkedHashMap<Integer,<List<String>>
我有一个很大的LinkedHashMap<Integer,<List<String>>
. 。
For example: 例如:
<86, ["abc","def","xyz"]>
<32, ["ugy","oop","bbb"]>
<..., ...........]>
What i want is when user type a Comma separated String(eg "abc,oop,bbb" ), i want to print out the key. 我想要的是当用户键入逗号分隔的字符串(例如“ abc,oop,bbb” )时,我想打印出密钥。 In these case keys are 86,32,32 . 在这些情况下,键为86,32,32 。 I can handle separete the String into an array by using .split(" "); 我可以使用.split(“”);将字符串分隔成一个数组。 but i don't know what is simplest way to search these Strings ? 但是我不知道搜索这些字符串的最简单方法是什么?
I would use a map of integers to sets, not lists, since using a set would make checking against the user input without regard to order relatively easy. 我将使用整数映射到集合,而不是列表,因为使用集合会使对照用户输入进行检查,而无需考虑顺序,这相对容易。 Doing the same check for a list would be harder. 对列表进行相同的检查会比较困难。
public Integer getKey(Map<Integer, Set<String>> map, String input) {
String[] parts = input.split(",");
for (Map.Entry<Integer, Set<String>> entry : map.entrySet()) {
Integer key = entry.getKey();
Set<String> value = entry.getValue();
if (value.size() != parts.length) {
continue;
}
int counter = 0;
for (String part : parts) {
if (value.contains(part)) {
++counter;
}
else {
break;
}
}
if (counter == value.size()) {
return key;
}
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.