简体   繁体   中英

Finding duplicated values in array and remove both of them?

OK I know for Set and how to remove duplicated items from list,

Set<Integer> setint = new LinkedHashSet<>();
for(int j=0;j<selectedList.size();j++){
    setint.add(selectedList.get(j));
}

but what I need is to remove both of them. For example if I have 1,2,3,3,4,5,6,7,7,8,9 what I need is to find what integers are duplicated and remove both value. So for this example I want to remove 3 and 7, so that I have new array 1,2,4,5,6,8,9 .

Logics

ex: ar=[1,2,3,3,4,5,6,7,7,8,9]

first copy duplicate values to another array and remove it now you got ar_removed=[1,2,3,5,6,7,8,9]

here another array you got ar_dup=[3,7]

now check with ar_removed and ar_dup

you can remove ar_dup values by condition. The result ar_fi=[1,2,4,5,6,8,9]

may it will help!

You can add the duplicates into a Set , then use list.removeAll(set) to remove all duplicate occurrences

    ArrayList<Integer> list = new ArrayList<Integer>() {{
        add(1);
        add(2);
        add(3);
        add(3);
        add(4);
        add(5);
        add(6);
        add(7);
        add(7);
        add(7);
        add(8);
        add(9);
    }};

    // Sort the list to have adjacent duplicates 
    ArrayList<Integer> templist = new ArrayList<>(list);
    Collections.sort(templist);

    // Get the duplicate numbers
    Set<Integer> duplicates = new HashSet<>();
    for (int i = 0; i < templist.size() - 1; i++) {
        if (templist.get(i).equals(templist.get(i + 1)))
            duplicates.add(templist.get(i));
    }

    // Remove the duplicates
    Log.d("LOG_TAG", "onCreate: " + list);
    list.removeAll(duplicates);
    Log.d("LOG_TAG", "onCreate: " + list);

Result:

D/LOG_TAG: onCreate: [1, 2, 3, 3, 4, 5, 6, 7, 7, 7, 8, 9]
D/LOG_TAG: onCreate: [1, 2, 4, 5, 6, 8, 9]

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