Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if List contains several elements in order

Let's say I have a List,

Arrays.asList("A","B","C","D");

Is there a convenience method in Java that allows me to check this List to see if the elements C and D are on this list in that order?

Something along the lines of:

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

Where the above methods will return true but

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

will not?

like image 542
Ryan_DS Avatar asked Oct 29 '25 08:10

Ryan_DS


1 Answers

There is a method in the java.util package that can help (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);

It prints:

true
true
false
like image 114
David Pérez Cabrera Avatar answered Oct 31 '25 02:10

David Pérez Cabrera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!