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"
?
Asked
Active
Viewed 165 times
1

Anivartin Anand
- 19
- 6
-
1You can sort string characters of both and check equal – Eklavya Jul 11 '20 at 06:03
-
1@Eklavya: +1: you're correct., But there could be problems with commas and spaces if the OP isn't careful. – paulsm4 Jul 11 '20 at 06:17
-
1@paulsm4 Yes you are right, then the better way is splitting by comma removing space and [compare two list equal](https://stackoverflow.com/questions/13501142/java-arraylist-how-can-i-tell-if-two-lists-are-equal-order-not-mattering?rq=1) – Eklavya Jul 11 '20 at 06:23
-
@Eklavya: you mean like [this](https://stackoverflow.com/a/62845623/421195) :)? – paulsm4 Jul 11 '20 at 16:39
-
@paulsm4 Not exactly same, compare list not set. See the linked question's answer in my previous comment – Eklavya Jul 11 '20 at 16:42
2 Answers
4
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");
}

Tim Biegeleisen
- 502,043
- 27
- 286
- 360
2
The string "a, b, c, d" is completely different from the string "b, c, d, a". They cannot ever be evaluated as "equal".
You CAN, however, parse the string. And save the elements "a", "b", "c" and "d" into a Collection, such as a List or a Set. TreeSet could be a good choice.
Optionally, you can also write a Comparitor for your collection.
The point is that you cannot evaluate the strings as-is. You must first choose an appropriate data structure for the string's contents. Only then can you evaluate and compare the values parsed from the string.

paulsm4
- 114,292
- 17
- 138
- 190