0

如何使用其中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();
}
4

2 回答 2

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);
        }
于 2013-05-16T10:31:51.930 回答
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
于 2013-05-16T10:29:29.610 回答