使用 Arraylist 从地图中的值获取键?
Get Key from Value in Map with Arraylist?
我正在 Java 中编写程序。我决定将 Map 与 ArrayList 结合使用。
public static Map<String, List<String>> users = new HashMap<>();
所以,我的问题并没有我想的那么复杂:如您所见,有一个 Key (String),每个 Key 都有一个自己的 ArrayList。我有一个方法,它获取我的地图(用户)的一个值。方法没那么重要。但是现在我想知道,哪个键(字符串)属于我的值,方法找到了哪个?
如果不维护一个不同的集合作为一种索引(可能有点矫枉过正),没有比遍历所有条目更好的方法了。
使用流
final String searchTerm = "whatever";
final String user = users.entrySet().stream()
.filter(entry -> entry.getValue().contains(searchTerm))
.findFirst()
.map(Map.Entry::getKey)
.orElseThrow(() -> new RuntimeException("No matching user for " + searchTerm));
祈使式
String user = null;
for (Map.Entry<String, List<String>> entry : users.entrySet())
{
if (entry.getValue().contains(searchTerm))
{
user = entry.getKey();
break;
}
}
if (user == null)
{
throw new RuntimeException("No matching user for " + searchTerm);
}
我正在 Java 中编写程序。我决定将 Map 与 ArrayList 结合使用。
public static Map<String, List<String>> users = new HashMap<>();
所以,我的问题并没有我想的那么复杂:如您所见,有一个 Key (String),每个 Key 都有一个自己的 ArrayList。我有一个方法,它获取我的地图(用户)的一个值。方法没那么重要。但是现在我想知道,哪个键(字符串)属于我的值,方法找到了哪个?
如果不维护一个不同的集合作为一种索引(可能有点矫枉过正),没有比遍历所有条目更好的方法了。
使用流
final String searchTerm = "whatever";
final String user = users.entrySet().stream()
.filter(entry -> entry.getValue().contains(searchTerm))
.findFirst()
.map(Map.Entry::getKey)
.orElseThrow(() -> new RuntimeException("No matching user for " + searchTerm));
祈使式
String user = null;
for (Map.Entry<String, List<String>> entry : users.entrySet())
{
if (entry.getValue().contains(searchTerm))
{
user = entry.getKey();
break;
}
}
if (user == null)
{
throw new RuntimeException("No matching user for " + searchTerm);
}