我希望能够测试 List 是否包含具有给定键值的对象
例如,我想做类似Iterables.contains(l2, "lname", "Jordan")); 而不必在 l2 中创建所有其他 Map 对象,如下所示
//List<String> l = Arrays.asList("Mickael", "Jordan", "His Airness");
//System.out.println(Iterables.contains(l, "Jordan"));
Map<String, String> p1 = new HashMap<String, String>();
p1.put("fname", "Mickael");
p1.put("lname", "Jordan");
p1.put("nname", "His Airness");
Map<String, String> p2 = new HashMap<String, String>();
p2.put("fname", "Paul");
p2.put("lname", "Pierce");
p2.put("nname", "The Truth");
List<Map<String, String>> l2 = Arrays.asList(p1, p2);
Map<String, String> p3 = new HashMap<String, String>();
p3.put("fname", "Mickael"); //
p3.put("lname", "Jordan");
p3.put("nname", "His Airness"); //
System.out.println(Iterables.contains(l2, p3));
我想知道是否有这样的番石榴的功能,而不是在 l2 上循环并测试每个 elt.get("lname")
编辑
回答了 3 个解决方案:尝试查看哪个更高效
System.out.println(Iterables.any(l2, withEntry("lname", "Jordan"))); //@axtavt
System.out.println(has("lname", "Jordan")); //@JB
System.out.println(Iterables.any(l2, new KeyValuePredicate("lname", "Jordan"))); //@JB
public static Boolean has(final String key, final String value) {
return Iterables.any(l2, new Predicate<Map<String, String>>() {
@Override
public boolean apply(Map<String, String> input) {
return input.get(key).equals(value);
}
});
}
public static Predicate<Map<String, String>> withEntry(final String key, final String value) {
return new Predicate<Map<String, String>>() {
public boolean apply(Map<String, String> input) {
return value.equals(input.get(key));
}
};
}
class KeyValuePredicate implements Predicate<Map<String, String>>{
private String key;
private String value;
public KeyValuePredicate(String key, String value) {
super();
this.key = key;
this.value = value;
}
@Override
public boolean apply(Map<String, String> arg0) {
// TODO Auto-generated method stub
return arg0.get(key).equals(value);
}
}