I need to add two lists of objects of the same type to a SET. I should make sure the order of the set is of natural order and there is no reparation in the SET.
I read answer of this question but it did not help.
For example my inputs and output should be as following
List 1
A A1 List1
B B1 List1
B B1 List1
List 2
C C1 List2
D D1 List2
A A1 List2
Output
List1
A A1
B B1
List2
C C1
D D1
As you can see the second B B1
does not exist in List 1
of the output because there are two B B1
on the list 1
.
Also A A1
does not exist in the list 2
of output because it already exists in List 1
of the output.
Also the order of each list is kept. (List 1 is added first so List 1 is on top of the list, after that List 2 and the order of all of their elements is preserved.)
public class MyList{
private String name;
private String code;
private String group;
//setters and getters
}
List<MyList> list1 = new ArrayList<MyList>();
List<MyList> list2 = new ArrayList<MyList>();
....
Set<MyList> output = new TreeSet<MyList>();
output.addAll(list1);
output.addAll(list2);
Exception that is thrown
java.lang.ClassCastException: com.myproject.MyList cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(TreeMap.java:1290)
at java.util.TreeMap.put(TreeMap.java:538)
at java.util.TreeSet.add(TreeSet.java:255)
at java.util.AbstractCollection.addAll(AbstractCollection.java:344)
at java.util.TreeSet.addAll(TreeSet.java:312)
To solve the issue I added Comparable to MyList class, but it changes the order of the SET. How to keep the natural order of the SET?