Java program to remove all duplicates words from a given sentence

JavaObject Oriented ProgrammingProgramming

To remove all duplicate words from a given sentence, the Java code is as follows −

Example

 Live Demo

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.

raja
Published on 07-Jul-2020 13:13:02
Advertisements