使用该TreeSet中的重复项并打印出重复项

时间:2013-05-16 10:24:31

标签: java duplicates 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();
}

2 个答案:

答案 0 :(得分: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);
        }

答案 1 :(得分: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