Comparator<T> is an interface
Stream sorted(Comparator comparator) returns the stream of elements in natural sorted order and reverse sorted order with the provided Comparator.
sorted(Comparator<? super T> comparator)
List<Integer> l = Arrays.asList(6, 9, -6, -9);
l.stream.sorted(Comparator.naturalOrder()).forEach(System.out::println);
l.stream.sorted(Comparator.reverseOrder()).forEach(System.out::println);
Example: class Medication has medOrderList as the property.
@Data @AllArgsConstructor @NoArgsConstructor @ToString
class Medication {
private List<MedOrder> medOrderList;
}
class MedOrder has medicationName, medicationDose, startDate as properties.
@Data @AllArgsConstructor @NoArgsConstructor @ToString
class medOrder {
private String medicationName;
private Double medicationDose;
private TimeStamp startDate;
}
list of medOrderList needs to be sorted in ascending(natural) order, the list can be sorted this way.
medOrderList.stream()
.sorted(Comparator.comparing(Medication::medicationName)).collect(Collectors.toList());
return medOrderList;
if list of medOrderList needs to be sorted in descending(reverse) order.
medOrderList.stream()
.sorted(Comparator.comparing(Medication::medicationName).reversed()).collect(Collectors.toList());
return medOrderList;
list of medOrderList needs to be sorted in descending(reverse) order and if there are same medications then sort on startDate(current date to previous), the list can be sorted this way.
medOrderList.stream()
.sorted(Comparator.comparing(Medication::medicationName).thenComparing(Medication::startDate, Comparator.reverseOrder()).reversed()).collect(Collectors.toList());
return medOrderList;
static <T> Comparator<T> nullsLast (Comparator<T> comparator)
public class nonNullsMethod {
public static void main(String[] args)
{
String[] names = { "keerthi", "deepthi", null,
"divya", "nitin", null};
Arrays.sort(strings,
Comparator.nullsLast(
Comparator.naturalOrder()));
System.out.println(Arrays.toString(strings));
}
} //refer to nitin JAVA STREAM ISSUES for example using list.