如何检查List是否按顺序包含多个元素

时间:2017-10-03 12:26:09

标签: java list arraylist

我们说我有一个名单,

Collections.containsOrderedElements(list,"C","D");
Collections.containsOrderedElements(list,"A","B","C");

Java中是否有一种便捷方法允许我检查此列表以查看元素C和D是否按此顺序列在此列表中?

有些事情:

Collections.containsOrderedElements(list,"A","C");

上述方法将返回true但

{{1}}

会不会?

感谢您的时间。

1 个答案:

答案 0 :(得分:12)

有一种方法可以提供帮助(Collections.indexOfSubList(sourceList,subList)):

List<String> list = Arrays.asList("A", "B", "C", "D");

System.out.println( (Collections.indexOfSubList(list, Arrays.asList("C", "D"))>= 0));
System.out.println( (Collections.indexOfSubList(list, Arrays.asList("A","B","C"))>= 0));
System.out.println( (Collections.indexOfSubList(list, Arrays.asList("A", "C"))>= 0));

打印:

true
true
false