Java program to remove all duplicates words from a given sentence


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.

Updated on: 07-Jul-2020

448 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements