Skip to content
Advertisement

Find the sequence in the String matches the items in the List

Suppose I have a list and then I add names to the list

List<String> listOfName = new ArrayList();
listOfName.add("abc");
listOfName.add("pqr");
listOfName.add("xyz");

And I have a String String names = "abcrnpqrrnxyz";

I want to verify that the string is comprised in the same order as the elements in the list are.

eg: abc should come first then pqr and then xyz

What I am trying to do:

int flag = 1;
for(int i=0; i<listOfName.size()-1;i++){
    if(names.replace("rn","").split(listOfName.get(i))[1].indexOf(listOfName.get(i+1))!=0){
        flag = 0;
        break;
    }
}
if(flag==1){
    System.out.println("True");
} else {
    System.out.println("False");
}

Is there any better solution for doing the same as I doubt that it might fail in some scenarios

Advertisement

Answer

Well, there is certainly a more “abstract” and semantically pretty way to do this:

public class CompareList {

    public static void main(String[] args) {
        List<String> listOfNames = new ArrayList<String>();
        listOfNames.add("abc");
        listOfNames.add("pqr");
        listOfNames.add("xyz");
        
        String names = "abcrnpqrrnxyz"; // define string
        boolean match = checkList(listOfNames, names, "rn"); //check match
        System.out.println(match); //print match
    }
    
    private static boolean checkList(
            List<String> list,
            String content,
            String delimiter) {
        
        return Arrays.asList(
                content.split(Pattern.quote(delimiter))).equals(list);
    }
    
}

This will print true.

Here you have method checkList() (or whatever name you like) that splits the string using the given delimiter (rn in your case), turns the resulting array into a List and just calls equals() on it to compare it with the input List, as the equals() implementation of List (i quote) “Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.”.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement