To remove all duplicate words from a given sentence, the Java code is as follows −
Example
import java.util.Arrays;
import java.util.stream.Collectors;
public class Demo{
public static void main(String[] args){
String my_str = "This is a is sample a sample only.";
my_str = Arrays.stream(my_str.split("\\s+")).distinct().collect(Collectors.joining(" "));
System.out.println(my_str);
}
}Output
This is a sample only.
A class named Demo contains the main function. In this function, a String object is defined. It is split based on the spaces and only distinct words of the string are joined together using space as a separator and displayed on the console.