4

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?

Thank you for your time.

2
  • Will the List always be sorted or can it be unsorted also?
    – Utsav
    Oct 3, 2017 at 12:30
  • 1
    Nope. No such method exists in core Java.
    – Joe C
    Oct 3, 2017 at 12:31

1 Answer 1

12

There is a method 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.