Java Program to Remove Duplicate Words from String

In this post, we will write Java program to count number of duplicate words in given string.
In this post, we will discuss two ways, we can write the program to count number of duplicate words in given String.
  • How to remove duplicate words from String in Java?
  • How to remove duplicate words from String using Java 8?

How to remove duplicate words from String in Java?

package com.javaguides.strings.examples;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * Java Program to Count Number of Duplicate Words in Given String
 * @author javaguides.net
 *
 */
public class RemoveDuplicateWordsFromString {
 public static void main(String[] args) {
  String string = "i like java java coding java and you do you interested in java coding coding.";

  System.out.println("Original String: ");
  System.out.println(string);
  /*
   * Since the words are separated by space, we will split the string by
   * one or more space
   */

  final String[] strWords = string.split("\\s+");

  // convert String array to LinkedHashSet to remove duplicates
  final Set<String> setOfWords = new LinkedHashSet<String>(Arrays.asList(strWords));

  // join the words again by space
  final StringBuilder builder = new StringBuilder();
  int index = 0;

  for (String s : setOfWords) {

   if (index > 0)
    builder.append(" ");

   builder.append(s);
   index++;
  }

  string = builder.toString();

  System.out.println("String after removing duplicate words: ");
  System.out.println(string);

 } 
}
Output:
Original String: 
i like java java coding java and you do you interested in java coding coding.
String after removing duplicate words: 
i like java coding and you do interested in coding.

How to remove duplicate words from String using Java 8?

Input for below program:
String string = "i like java java coding java and you do you interested in java coding coding.";
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * Java Program to Count Number of Duplicate Words in Given String using java 8
 * 
 * @author javaguides.net
 *
 */
public class RemoveDuplicateWordsFromString {
 public static void main(String[] args) {

  String string = "i like java java coding java and you do you interested in java coding coding.";

  string = Arrays.stream(string.split("\\s+")).distinct().collect(Collectors.joining(" "));

  System.out.println(string);

 }
}
Output:
i like java coding and you do interested in coding.
Note that the number of lines of code in both programs.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Related String Programs

Note that these programs are asked in interviews.

Comments