You can combine the two lists in a HashSet
. In that case, the duplicates will be eliminated and the elements will be ordered without any additional manipulation.
Sample code:
List<String> listA = new ArrayList<>(Arrays.asList("z","a", "b", "c"));
List<String> listB = new ArrayList<>(Arrays.asList("e","a", "b", "z", "c", "d"));
Set<String> setCombined = new HashSet<>(listA);
setCombined.addAll(listB);
System.out.println(setCombined);
List<String> listCombined = new ArrayList<>(setCombined);
System.out.println(listCombined);
Here, both in setCombined
and in listCombined
you will have your items without duplicates and ordered, you can use any of the two to present the data according to your requirements.
The output on the screen is this:
[a, b, c, d, e, z]
[a, b, c, d, e, z]
Here, you can see a DEMONSTRATION IN REXTESTER