2

This is my program to remove duplicate words in a string using set the program works fine removing duplicate elements, but the output is not in the correct order

public class Remove_DuplicateIN_String {

    public static void main(String a[]) throws IOException {
        String a1;//=new String[200];
        int i;
        InputStreamReader reader=new InputStreamReader(System.in);
        BufferedReader in =new BufferedReader(reader);
        System.out.println("Enter the String ");
            a1=(in.readLine());
            System.out.print(a1);
        System.out.println("\n");
        String words[]=new String[100];
        words=a1.split(" ");
        System.out.println(words.length);
        Set<String> uniq=new HashSet<String>();
        for(i=0;i<words.length;i++)
        {
            uniq.add(words[i]);
        }
        Iterator it=uniq.iterator();
        while(it.hasNext())
        {
            System.out.print(it.next()+" ");
        }
    }
}

Enter the String hi hi world hello a

hi hi world hello a

5

hi a world hello

I want output as hi world hello a

bhansa
  • 7,282
  • 3
  • 30
  • 55

4 Answers4

2

Use LinkedHashSet

It maintains order and avoid duplicates.

Set wordSet = new LinkedHashSet();
Napolean
  • 5,303
  • 2
  • 29
  • 35
1

Use LinkedHashSet.

It will track order and also avoid duplicates of elements.

Set<String> linkedHashSet = new LinkedHashSet<String>();

If you have already stored elements in array of strings, you can use collection api to addAll into set.

String words[]=a1.split(" ");

Set<String> linkedHashSet=new LinkedHashSet<String>();
linkedHashSet.addAll(Arrays.asList(words));.
nagendra547
  • 5,672
  • 3
  • 29
  • 43
0
package StringPrograms;

import java.util.Scanner;

public class RemoveDuplicateWords {

    public static void main(String[] args) {
        boolean flag;
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        String[] str = input.split(" ");
        int count = 0;
        String[] out = new String[str.length];
        for (int i = 0; i < str.length; i++) {
            flag = true;
            for (int j = 0; j <count; j++) {
                if (str[i].equalsIgnoreCase(out[j])) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                out[count] = str[i];
                count++;
            }
        }
        for (int k = 0; k < out.length; k++) {
            if (out[k] != null)
                System.out.print(out[k] + " ");
        }
    }
}
Alexandra Dudkina
  • 4,302
  • 3
  • 15
  • 27
0
String noDuplicates = Arrays.asList(startingString.split(" ")).stream()
                            .distinct()
                            .collect(Collectors.join(" "));

This approach doesn't handle commas and special characters though.