如何使用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();
}
答案 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