fork(2) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.stream.*;
  7. import java.util.function.*;
  8.  
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone
  11. {
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. List<Function<? super Data, ? extends Comparable>> extractors = new ArrayList<>();
  15. extractors.add(Data::getA);
  16. extractors.add(Data::getB);
  17.  
  18. Comparator<Data> test = parseKeysAscending(extractors);
  19.  
  20. List<Data> data = new ArrayList<>(Arrays.asList(
  21. new Data(1, "z"),
  22. new Data(2, "b"),
  23. new Data(1, "a")));
  24.  
  25. System.out.println(data); // [[1, 'z'], [2, 'b'], [1, 'a']]
  26.  
  27. data.sort(test);
  28.  
  29. System.out.println(data); // [[1, 'a'], [1, 'z'], [2, 'b']]
  30. }
  31.  
  32. public static <T, S extends Comparable<? super S>> Comparator<T> parseKeysAscending(List<Function<? super T, ? extends S>> keyExtractors) {
  33. if (keyExtractors.isEmpty()) {
  34. return (a, b) -> 0;
  35. } else {
  36. Function<? super T, ? extends S> firstSortKey = keyExtractors.get(0);
  37. List<Function<? super T, ? extends S>> restOfSortKeys = keyExtractors.subList(1, keyExtractors.size());
  38. return Comparator.comparing(firstSortKey).thenComparing(parseKeysAscending(restOfSortKeys));
  39. }
  40. }
  41.  
  42. public static class Data {
  43. private final Integer a;
  44. private final String b;
  45.  
  46. private Data(int a, String b) {
  47. this.a = a;
  48. this.b = b;
  49. }
  50.  
  51. public Integer getA() {
  52. return a;
  53. }
  54.  
  55. public String getB() {
  56. return b;
  57. }
  58.  
  59. @Override
  60. public String toString() {
  61. return "[" + a + ", '" + b + "']";
  62. }
  63. }
  64. }
  65.  
Success #stdin #stdout 0.14s 2184192KB
stdin
Standard input is empty
stdout
[[1, 'z'], [2, 'b'], [1, 'a']]
[[1, 'a'], [1, 'z'], [2, 'b']]