Reputation: 117
I have such a situation:
@Getter
@Setter
public class ObjectA {
private Integer id;
private String code;
private String name;
}
@Getter
@Setter
public class ObjectB {
private Integer id;
private Timestamp createdOn;
}
I have to sort a List<ObjectA>
which also contains the ids of the List<ObjectB>
and the sorting must be:
List<ObjectB>
included in the List<ObjectA>
and distinguishable from the idsWith this i sort by name and code with .sort() and comparators:
listA.sort(o -> o.getName())
.thenComparing(o -> o.getCode()).reversed();
The part that I cannot produce is the sorting of the list based on an attribute that is not present in the list that is being sorted but in another distinguishable by ids.
Thank u all for the help.
Upvotes: 1
Views: 118
Reputation: 2202
Maybe you need something like this:
Map<Integer, Timestamp> mapOfB = listB.stream()
.collect(Collectors.toMap(ObjectB::getId,
ObjectB::getCreatedOn));
listA.sort(Comparator.comparing(o-> mapOfB.get(((ObjectA)o).getId()),
Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(o->((ObjectA)o).getName())
.thenComparing(o->((ObjectA)o).getCode(), Comparator.reverseOrder()));
Upvotes: 2
Reputation: 1859
I'd recommend you convert list of ObjectB into a Map<id, createdOn>
as retrieving elements by key is O(1) in Map but O(n) in List.
Map<Integer, Timestamp> createdOnMap =
bList.stream().collect(Collectors.toMap(ObjectB::getId, ObjectB::getCreatedOn));
Then compare by getting the value of this map, and if it's not present decide whether to place it as first or last in the list by comparing the value against a maximum/minimum value. An example with LocalDateTime:
aList.stream()
.sorted(Comparator.comparing(objectA -> createdOnMap.getOrDefault(objectA.getId(), LocalDateTime.MAX)))
.collect(Collectors.toList())
In the scenario that createdOnMap doesn't have a value for this id, it compares against LocalDateTime.MAX/MIN
.
If you also want to have in the final list elements that are not present in List but are in List, then you'll need to add those elements by yourself before sorting by converting ObjectB to ObjectA.
Upvotes: 2