比较两个列表,并找到第一个的所有元素是否也在第二个
我有两个String对象的Java列表,我想要的是一个方法,如果我的第一个列表中的所有元素都是返回true
也是第二个元素。比较两个列表,并找到第一个的所有元素是否也在第二个
例如:
List<String> validCombination: [3, 5, 12]
List<String> currentCombincation: [2, 3, 4, 5, 7, 12, 14]
由于currentCombination
有validCombination
我的方法的所有元素应该返回true
。
在currentCombination
缺少validCombination
的一个或多个元素的情况下,例如,
List<String> validCombination: [3, 5, 12]
List<String> currentCombincation: [2, 4, 5, 7, 12, 14]
它应该返回false
。
关于如何在Java中实现它的任何想法?
如果列表包含给定Collection
的所有元素,则可以使用List#containsAll(Collection<?> c)
方法返回true
。例如:
boolean containsAll = currentCombination.containsAll(validCombination);
既然你需要一种方法,它可以这样写:
public static boolean contains(List<?> currentCombination, List<?> validCombination) {
return currentCombination.containsAll(validCombination);
}
请注意,该方法可能是静态的。 – chrylis 2014-12-13 11:11:18
@chrylis,有道理,是的。我已更正它,谢谢 – 2014-12-13 11:36:10
boolean containsAll(Collection<?> args)
是您可以使用您的解决方案
为
方法if(currentCombincation.containsAll(validCombination))
{
return true;
}
Whic您使用的是Java版本? – 2014-12-13 10:55:20
也可以使用'List'。我不明白为什么它会是'List '。 –
2014-12-13 10:57:10