fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.io.*;
  4. import java.lang.*;
  5. import java.util.*;
  6. import java.util.Comparator;
  7. import java.util.concurrent.*;
  8. import java.util.function.*;
  9. import java.util.stream.*;
  10.  
  11. class Car {
  12. int num;
  13. String engine;
  14.  
  15. public Car(int num, String engine) {
  16. this.num = num;
  17. this.engine = engine;
  18. }
  19.  
  20. public Integer getNum() {
  21. return this.num;
  22. }
  23.  
  24. public String getEngine() {
  25. return this.engine;
  26. }
  27.  
  28. public String toString() {
  29. return String.format("Car: %d, %s", num, engine);
  30. }
  31. }
  32.  
  33. /* Name of the class has to be "Main" only if the class is public. */
  34. class Ideone {
  35. public static <T> Predicate<T> distinctByKey(
  36. Function<? super T, ?> keyExtractor) {
  37. Set<Object> seen = ConcurrentHashMap.newKeySet();
  38. return t -> seen.add(keyExtractor.apply(t));
  39. }
  40.  
  41. public static Comparator<Car> withNullEnginesLast() {
  42. return Comparator.comparing(Car::getNum)
  43. .thenComparing(
  44. Car::getEngine, Comparator.nullsLast(Comparator.naturalOrder()));
  45. }
  46.  
  47. public static void main(String[] args) throws java.lang.Exception {
  48. // your code goes here
  49.  
  50. var carList = List.of(
  51. // num, engine
  52. new Car(1, "S02K"), new Car(1, null), new Car(2, null),
  53. new Car(2, "S9K"), new Car(3, null));
  54.  
  55. var result =
  56. carList.stream()
  57. .sorted(withNullEnginesLast()) // sort first by num, then engine
  58. // where null-engines last
  59. .filter(distinctByKey(Car::getNum))
  60. .collect(Collectors.toList());
  61.  
  62. System.out.println(result);
  63. }
  64. }
Success #stdin #stdout 0.13s 42952KB
stdin
Standard input is empty
stdout
[Car: 1, S02K, Car: 2, S9K, Car: 3, null]