1

I have an ArrayList of Set of Strings; ArrayList<Set<String>> tmp

I need to use this type of data structure because of my requirement. How can I remove duplicates from this?

For example, how to convert;

[[A, B, C], [B, A, C], [C, D, E], [E, C, D]]

to

[[A, B, C], [C, D, E]]

I did go through the other similar answers here, but they are concatenating all the items into one list, for the above example [[A, B, C, D, E, F]] I DONOT want this

hsnsd
  • 1,728
  • 12
  • 30

3 Answers3

1

the same way you remove duplicates from any other ArrayList...

For example:

tmp.stream().distinct().collect(Collectors.toList());

Note: this assumes that the list items implement a suitable equals method. As they should.

Patrick Parker
  • 4,863
  • 4
  • 19
  • 51
0

One way to do it:

    List<Set<String>> tmp = new ArrayList<>();
    tmp.add(new HashSet<>(List.of("A", "B", "C")));
    tmp.add(new HashSet<>(List.of("B", "A", "C")));
    tmp.add(new HashSet<>(List.of("C", "D", "E")));
    tmp.add(new HashSet<>(List.of("E", "C", "D")));

    Iterator<Set<String>> it = tmp.iterator();
    while (it.hasNext())
    {
        Set<String> currentSet = it.next();

        for (Set<String> set : tmp)
        {
            if (currentSet != set
                    && currentSet.containsAll(set)
                    && currentSet.size() == set.size())
            {
                it.remove();
                break;
            }
        }
    }

    System.out.println(set);

Output:

[[A, B, C], [C, D, E]]
Ealrann
  • 368
  • 1
  • 15
0

HashSet is working on hash algorithm,

So if you have two Set of String which contains the same value then hashcode of that set will always be same (As String has special allocation in java).

So you can try like below.

    List<Set<String>> tmp = new ArrayList<Set<String>>();
    tmp.add(new HashSet<>(Arrays.asList(new String[]{"A","B","C"})));
    tmp.add(new HashSet<>(Arrays.asList(new String[]{"B","A","C"})));
    tmp.add(new HashSet<>(Arrays.asList(new String[]{"C","D","E"})));
    tmp.add(new HashSet<>(Arrays.asList(new String[]{"E","C","D"})));

    List<Set<String>> list =new ArrayList<>();

    for(Set<String> s: tmp){
        if(!list.contains(s)){
            list.add(s);
        }
    }
    System.out.println(list);

Will result like

[[A, B, C], [C, D, E]]
Alpesh Jikadra
  • 1,692
  • 3
  • 18
  • 38