gpt4 book ai didi

java - 如何获取 MultiMap 值中元素的索引

转载 作者:行者123 更新时间:2023-12-01 09:02:02 27 4
gpt4 key购买 nike

我想检查元素“Item Two”是否在 MultiMap 的值中获取该元素的索引,下面是我的代码。

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.MultiMap;
import org.apache.commons.collections.map.MultiValueMap;

public class Test {
public static void main(String args[]) {
MultiMap mhm = new MultiValueMap();
String key ="";
key = "Group One";
mhm.put(key, "Item One");
mhm.put(key, "Item Two");
mhm.put(key, "Item Three");

key = "Group Two";
mhm.put(key, "Item Four");
mhm.put(key, "Item Five");

Set keys = mhm.keySet();
for (Object k : keys) {
System.out.println("+k+“ : "+mhm.get(k)+")");
List benefit = new ArrayList();
benefit.add(mhm.get(k));
System.out.println("+value at is+“ : "+benefit.contains("Item One")+")");
}
}
}

输出是:

mhm-keys : [Item One, Item Two, Item Three]
value at is : false
mhm-keys : [Item Four, Item Five]
value at is : false

您能帮忙吗,因为我无法使用除 MultiMap 之外的其他东西

最佳答案

首先,MultiValueMap 已被弃用,您应该使用 MultiValuedMap 代替。 https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MultiValuedMap.html

MultiValuedMap<String, String> mhm = new ArrayListValuedHashMap<String, String>();

但是如果您想使用已弃用的 MultiValueMap,我也可以。对于两者,您可以使用以下内容:

mhm.containsValue(value);

您还可以使用:

List<String> itemsWithKey = mhm.get(key);
System.out.println(itemsWithKey.contains(value));

更新:这对我有用:

MultiMap mhm = new MultiValueMap();
String key ="";
key = "Group One";
mhm.put(key, "Item One");
mhm.put(key, "Item Two");
mhm.put(key, "Item Three");

key = "Group Two";
mhm.put(key, "Item Four");
mhm.put(key, "Item Five");

System.out.println(mhm.containsValue("Item One"));
System.out.println(mhm.containsValue("Item Nine"));

这将返回:

true
false

更新2这会检查所有键中的“第四项”,并为每个键返回 true/false

MultiMap mhm = new MultiValueMap();
String key ="";
key = "Group One";
mhm.put(key, "Item One");
mhm.put(key, "Item Two");
mhm.put(key, "Item Three");

key = "Group Two";
mhm.put(key, "Item Four");
mhm.put(key, "Item Five");


Set<String> keys = mhm.keySet();

String itemToLookFor = "Item Four";

for(String k : keys) {
List<String> itemsWithKey = (List<String>) mhm.get(k);
boolean doesExists = itemsWithKey.contains(itemToLookFor);
System.out.println("does " + itemToLookFor + " exists for key " + k + ": " +doesExists);
}

结果是:

does Item Four exists for key Group One: false
does Item Four exists for key Group Two: true

关于java - 如何获取 MultiMap 值中元素的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41588374/

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