简体   繁体   中英

using Collections.binarySearch to remove duplicates from a pre-populated ArrayList

For an assignment, I have been given the task of reading in a pre-populated file as an ArrayList, sorting it, and removing all duplicates. I have been tasked to doing this with the binarySearch API. He's being rather specific. I have never done this before, and I'm not sure what I need to do to get Collections.binarySearch to work. The instructor gave me a start, but I know I am doing the parameters of Collections.binarySearch incorrectly, but I cannot for the life of me figure out the correct way to do this. If anyone can help out, it would be greatly appreciated.

This is what I have so far. If it matters at all, I can post the integers from set1.txt

public static void main(String[] args) {
    collections program = new Collections();
    program.readFile();
}//main

public void readFile() {
    File f = new File("set1.txt");
    try {
        Scanner in = new Scanner(f);
        while (in.hasNext()) {
            int x = in.nextInt();
            int index = Collections.binarySearch(x,0);
            if (index == 1)
                list.add(x);
        }//while
        Collections.sort(list);

        in.close();
    }//try
    catch (IOException e) {
        e.printStackTrace();
    }//catch
}//readFile

Once you've sorted the list, duplicate elements (if any) will be next to one another, so you can simply iterate over the list removing any duplicate elements, no searching required. (We iterate backwards to avoid the awkwardness of deciding whether to increment the loop counter after removing an element.)

Collections.sort(list);
for (int i = list.size()-1; i >= 0; --i)
    if (list.get(i).equals(list.get(i+1)))
        list.remove(i);

But a more convenient way to ensure uniqueness is to create a Set holding the contents of your list, then create a new list from the set. The new list will contain the unique elements of the input list in the set's iteration order, so we can sort at the same time by using a TreeSet . (Using a HashSet to create the list, then calling Collections.sort(list) may or may not be faster, and the above solution may be faster still -- if it matters to you, profile to ensure it's a problem, then benchmark.)

list = new ArrayList<>(new TreeSet<>(list));

If reusing the input list is important (either as an arbitrary homework requirement or to minimize memory use/churn), you can do something like

Set<T> set = new TreeSet<>(list);
list.clear();
list.addAll(set);

由于新的Java已经发布,因此我不妨张贴此文章以帮助“未来的寻求者”。

ArrayList<String> newList = oldList.stream().distinct().collect(Collectors.toCollection(ArrayList::new));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM