Check whether two strings have same contents regardless of word order

You could count the occurences of every word in each String and compare the results :

String phrase = "Long sentences may be used for several reasons: To develop tension. While a short sentence is the ultimate sign of the tension, long sentences could be used to develop this tension to a point of culmination. To give vivid descriptions.";
String phrase2 = "Long sentences may be used for several reasons: To develop tension. While a short sentence is the sign ultimate of the tension, long sentences could be used to develop this tension to a point of culmination. To give vivid descriptions.";
      
Map<String,Long> wordCount = Arrays.stream(phrase.toLowerCase().split("\\W+"))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        
Map<String,Long> wordCount2 = Arrays.stream(phrase2.toLowerCase().split("\\W+"))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        
System.out.println(wordCount.equals(wordCount2));
  • The first step is to apply toLowerCase() to your String. Remove this step if you want your comparison to be case sensitive.
    • "Hello world" => "hello world"
  • Then you split() the String around the matches of the following regex : \W+ to obtain an array. This regex matches one or more non-word character.
    • "hello world" => ["hello", "world"]
  • You call Arrays.stream() on this array to get a Stream.
  • You collect the elements of the Stream using Collectors.groupingBy() to associate every word with its number of occurences. Function.identity() is a function that returns its input.
    • {"hello": 1, "world": 1}