/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.stream.*;
import java.util.function.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
{
List<Function<? super Data, ? extends Comparable>> extractors = new ArrayList<>();
extractors.add(Data::getA);
extractors.add(Data::getB);
Comparator<Data> test = parseKeysAscending(extractors);
List
<Data
> data
= new ArrayList
<>(Arrays.
asList( new Data(1, "z"),
new Data(2, "b"),
new Data(1, "a")));
System.
out.
println(data
); // [[1, 'z'], [2, 'b'], [1, 'a']]
data.sort(test);
System.
out.
println(data
); // [[1, 'a'], [1, 'z'], [2, 'b']] }
public static <T, S extends Comparable<? super S>> Comparator<T> parseKeysAscending(List<Function<? super T, ? extends S>> keyExtractors) {
if (keyExtractors.isEmpty()) {
return (a, b) -> 0;
} else {
Function<? super T, ? extends S> firstSortKey = keyExtractors.get(0);
List<Function<? super T, ? extends S>> restOfSortKeys = keyExtractors.subList(1, keyExtractors.size());
return Comparator.
comparing(firstSortKey
).
thenComparing(parseKeysAscending
(restOfSortKeys
)); }
}
public static class Data {
private Data
(int a,
String b
) { this.a = a;
this.b = b;
}
return a;
}
return b;
}
@Override
return "[" + a + ", '" + b + "']";
}
}
}
LyogcGFja2FnZSB3aGF0ZXZlcjsgLy8gZG9uJ3QgcGxhY2UgcGFja2FnZSBuYW1lISAqLwoKaW1wb3J0IGphdmEudXRpbC4qOwppbXBvcnQgamF2YS5sYW5nLio7CmltcG9ydCBqYXZhLmlvLio7CmltcG9ydCBqYXZhLnV0aWwuc3RyZWFtLio7CmltcG9ydCBqYXZhLnV0aWwuZnVuY3Rpb24uKjsKCi8qIE5hbWUgb2YgdGhlIGNsYXNzIGhhcyB0byBiZSAiTWFpbiIgb25seSBpZiB0aGUgY2xhc3MgaXMgcHVibGljLiAqLwpjbGFzcyBJZGVvbmUKewoJcHVibGljIHN0YXRpYyB2b2lkIG1haW4gKFN0cmluZ1tdIGFyZ3MpIHRocm93cyBqYXZhLmxhbmcuRXhj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