Search code examples
javastringstring-comparison

Is there a way to compare strings disregarding the order of objects in a series of commas?


For example if had a string "a, b, c, d", is it possible to set another string equal to this one if the other string is "b, c, d, a"?


Solution

  • Assuming you don't have to worry about duplicates, you could convert both CSV strings into sets, and then compare:

    String input1 = "a, b, c, d";
    String input2 = "b, c, d, a";
    Set<String> set1 = new HashSet<>(Arrays.asList(input1.split(",\\s*")));
    Set<String> set2 = new HashSet<>(Arrays.asList(input2.split(",\\s*")));
    
    if (set1.equals(set2)) {
        System.out.println("EQUAL");
    }
    else {
        System.out.println("NOT EQUAL");
    }