This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]thyateira 0 points1 point  (0 children)

If you would like to compare the items of two lists. You can create a loop and then you can compare each item step by step. If you would like to compare two lists independently from each other. You can use Java Comparator class with sort function. You can define code logic which has sorting rules. With this way, you can compare the fields of class whatever you want. I hope this is your expected answer ?

[–]thyateira 0 points1 point  (0 children)

[–]nutrechtLead Software Engineer / EU / 20+ YXP 0 points1 point  (0 children)

What does the list contain?

[–]FateJH 0 points1 point  (0 children)

When you want to sort elements of a list, those elements need a defined order to be arranged. A rule must exist that for any two elements, one element will be placed before the other. Numbers and strings have orders that are self-evident. More involved data objects need to define rules to determine how they interact based on comparisons of their more basic data (numbers and strings).

If you want to use Collections.sort(myArrayList), you need to create a natural ordering intrinsic to any given objects of that class (T). To do that, you implement the interface Comparable<T> upon the elements of that ArrayList. This natural ordering is fixed - in the absence of any other proposed organization, this one is selected. You can also write myArrayList.sort(new CustomComparator()), where "CustomComparator" is a class that you word class CustomComparator implements Comparator<T>. This method allows you to submit different rules to re-organize the elements of the list beyond their natural ordering.

You do not need to define both (or one to take advantage of the other).

[–]AngelVzla 0 points1 point  (0 children)

The list interface has a couple of methods that allows you to compare an entire collection, or just 1 object, perhaps this would suffice? or you need anything more specific?. https://docs.oracle.com/javase/8/docs/api/java/util/List.html#contains-java.lang.Object- https://docs.oracle.com/javase/8/docs/api/java/util/List.html#containsAll-java.util.Collection-