简体   繁体   中英

How to compare 2 statements in java

Is it possible to compare 2 String like this.

String test1 = "foo bar abc";
String test2 = "bar abc foo";

Typically is not a String equals in java.

I'm thinking to use ArrayList or array by splitting string by space and compare.

Is there any other methods available? which one is better?

I want answer foo bar abc and bar abc foo are the same. I want to know if the same words appear in both or not.

If your strings represent sets of words (ie collections with no duplicates), the natural solution would be to use Sets :

    String test1 = "foo bar abc";
    String test2 = "bar abc foo";

    HashSet<String> set1 = new HashSet<>(Arrays.asList(test1.split(" ")));
    HashSet<String> set2 = new HashSet<>(Arrays.asList(test2.split(" ")));

    System.out.println(set1.equals(set2));

You can split two strings, sort result arrays and compare them.

public static void main(String[] args) {

    String test1 = "foo bar abc";
    String test2 = "bar abc foo";

    System.out.println(method(test1, test2));
}


private static boolean method(String test1, String test2){
    String[] tokens1 = test1.split(" ");
    String[] tokens2 = test2.split(" ");

    Arrays.sort(tokens1);
    Arrays.sort(tokens2);

    return Arrays.equals(tokens1, tokens2);
}

You can make a list out of each string, by splitting both strings into separate words (using regex).
Then you can check if the second list contains all the values that are in the first list:

String test1 = "foo bar abc";
String test2 = "bar abc foo";
List<String> list1 =Arrays.asList(test1.split("\\s+"));
List<String> list2 =Arrays.asList(test2.split("\\s+"));
if(!list2.containsAll(list1))
    return false;//or print out "false", whichever suits you

That's is one of many possibilities:

import java.util.Arrays;

(...)

String test1 = "foo bar abc";
String test2 = "bar abc foo";

if (Arrays.asList(test1.split("\\s+")).containsAll(Arrays.asList(test2.split("\\s+")))) {
    return true;
} else {
    return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM