2013-05-16 69 views
0

如何使用該副本從TreeSet打印重複項?使用TreeSet中的副本並將副本打印出來

我創建了一個方法,允許我填充一個沒有文本文件重複的數組,現在我需要讓這些重複文件在另一個文件中編寫它們。我怎麼做?

// method that gets that reads the file and puts it in to an array 
public static void readFromfile() throws IOException { 
    // Open the file. 
    File file = new File("file.txt"); 
    Scanner inputFile = new Scanner(file); 

    // create a new array set Integer list 
    Set<Integer> set = new TreeSet<Integer>(); 
    // add the numbers to the list 
    while (inputFile.hasNextInt()) { 
     set.add(inputFile.nextInt()); 
    } 
    // transform the Set list in to an array 
    Integer[] numbersInteger = set.toArray(new Integer[set.size()]); 

    // loop that print out the array 
    for (int i = 0; i < numbersInteger.length; i++) { 
     System.out.println(numbersInteger[i]); 
    } 

    // close the input stream 
    inputFile.close(); 
} 
+1

使用代碼塊一致性和邏輯縮進。代碼的縮進旨在幫助人們理解程序流程! –

+2

使用'set.add(inputFile.nextInt());' –

回答

2
List<Integer> duplicates = new ArrayList<Integer>(); 
     Set<Integer> set = new TreeSet<Integer>(); 
     // add the numbers to the list 
     while (inputFile.hasNextInt()) { 
      Integer it = inputFile.nextInt(); 
      if (set.contains(it)) { 
       duplicates.add(it); // adding duplicates which is already present in Set 
      } else { 
       set.add(it); // if not present in set add to Set 
      } 
     } 

// loop ArrayList print duplicates values 
+0

的返回值,這也適用:'if(!set.add(it)){duplicates.add(it); }' –

4

你可以收集重複同時加入到TreeSet或任何Set

List<Integer> dups = new ArrayList<Integer>(); 
     Set<Integer> noDups= new TreeSet<Integer>(); 
int i; 
     while (inputFile.hasNextInt()) { 
     { 
      if(!noDups.add(i=inputFile.nextInt())) 
       dups.add(i); 
     } 
+0

什麼是(i)? –

+0

@WagnerMaximiliano它是'nextInt',更新後的代碼 – harsh