How to remove duplicates and matching original elements from list using java

Viewed 53

I have already tried using a Set Collection to remove duplicates but this does not solve what i am asking here.

I am trying to accomplish the following task: I have a list Integer [] list1 = {1,2,3,3}; i want to remove the duplicates but also I want to remove the matching pair, so the result i want is {1,2}

3 Answers

I would use a frequency map to filter the elements having a frequency greater than 2.

  • The frequency map freqMap has the entries: {1=1, 2=1, 3=2}, we just need to filter the entries having a value greater than 2 .filter(e -> e.getValue()<2) which is {3=2} here.
  • Now we have the entries: {1=1, 2=1} But we want only the keys {1, 2} so we use map() function to get the keys: .map(e -> e.getKey())

Try this:

Map<Integer, Long> freqMap = Arrays.stream(list1)
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

int[] result = freqMap.entrySet().stream()
        .filter(e -> e.getValue() < 2).map(e -> e.getKey()).mapToInt(m -> m).toArray();

System.out.println(Arrays.toString(result));

Output:

[1, 2]

You can use a Map. Count the number of times the elements appear in a <int, int> map and get only those keys that have a count of 1.

so then this is what you have for your example,

{

  1: 1,
  2: 1,
  3: 2,

}

Then just extract keys 1 and 2 since they have a count of 1. O(n) time and space.

My first thought was to get a set from the list, then remove all elements in the list that are in the set, and remove all elements in the set that are in the remaining list.

    Integer[] arr = { 1, 2, 3, 3 };
    List<Integer> list = new ArrayList<>(Arrays.asList(arr));
    Set<Integer> set = new HashSet<>(list);
    for (Iterator<Integer> iterator = set.iterator(); iterator.hasNext();) {
        list.remove(iterator.next());
    }
    set.removeAll(list);
    System.out.println(list);
    System.out.println(set);

Output:

[3]
[1, 2]

This will work with versions of Java less than Java 8. Otherwise just use freqMap() as answered by Hülya.

Related