I have two objects each with an id and a list.I would like to have a third arraylist sorting this object according to the list size.and still have the correaponding id along with the list
Here's the approach:
Create a
Comparator
which can compare two of the "id/list pairs" -- in this case, we compare the list sizes of the list component.Create an
ArrayList
of these "id/list pairs".Use the
Collections.sort
method to sort theArrayList
, according to theComparator
.
If I understand correctly, there is a id/list pair. Here's one I made:
class IdListPair {
int id;
List<?> list;
IdListPair(int id, List<?> list) {
this.id = id;
this.list = list;
}
public String toString() {
return "id: " + id + "; list: " + list;
}
}
The IdListPair
provides a constructor to create the id/list pair, and a toString
method which will be used later to show the results of the sort.
Then, we'll have a section that creates an ArrayList
, and sorts the list, using a Comparator
:
List<IdListPair> pairList = new ArrayList<IdListPair>();
pairList.add(new IdListPair(0, Arrays.asList(1, 2, 3)));
pairList.add(new IdListPair(1, Arrays.asList(1)));
pairList.add(new IdListPair(2, Arrays.asList(1, 2)));
System.out.println("Before: " + pairList);
Collections.sort(pairList, new Comparator<IdListPair>() {
public int compare(IdListPair o1, IdListPair o2) {
return o1.list.size() - o2.list.size();
}
public boolean equals(Object o) {
return false;
}
});
System.out.println("After: " + pairList);
At first, an ArrayList
was created with IdListPair
that has lists of differing lengths.
Then, the Collections.sort
method performs a sort according to the rules provided by the Comparator
. A class implementing Comparator
needs to provide the compare
and equals
methods.
Here, a Comparator
was made so it will compare the size
of the list
that each IdListPair
object contains in the compare
method. The equals
method is a dummy method as it isn't used here.
Most of the effort is going to come in writing the correct compare
method, so the sorter of Collections.sort
can correctly sort the list.
The results were as follows:
Before: [id: 0; list: [1, 2, 3], id: 1; list: [1], id: 2; list: [1, 2]]
After: [id: 1; list: [1], id: 2; list: [1, 2], id: 0; list: [1, 2, 3]]