- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.
Advertisements