2017-09-09 25 views
2

显示他们这是我的计划,以消除串的重复单词,使用设置 工作正常删除重复元素的程序,但输出是不正确的顺序如何删除重复的单词串,并在相同的顺序

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()+" "); 
     } 
    } 
} 

输入字符串 喜喜的世界问好一个

喜喜的世界问好一个

喜世界你好

我想为喜世界你好一个

+0

https://stackoverflow.com/questions/10752753/java-set-retain-order这可能有助于 –

回答

2

使用LinkedHashSet

输出它维持秩序,避免重复。

Set wordSet = new LinkedHashSet(); 
+0

想,如果输入的是doooone输出即完成如何在Word –

+0

字符串转换为删除重复的字符字符。框字符作为字符,你也可以使用LinkedHashSet – Napolean

1

使用LinkedHashSet。

它会跟踪顺序,并避免重复元素。

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

如果已经存储了字符串数组中的元素,可以使用collection api将addAll添加到set中。

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

Set<String> linkedHashSet=new LinkedHashSet<String>(); 
linkedHashSet.addAll(Arrays.asList(words));. 
相关问题