Skip to content

Instantly share code, notes, and snippets.

@qbosen
Created July 23, 2020 06:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qbosen/89aa4eb9c9e7eab3d4a380483ef01b2d to your computer and use it in GitHub Desktop.
Save qbosen/89aa4eb9c9e7eab3d4a380483ef01b2d to your computer and use it in GitHub Desktop.
fluent comparing
package top.abosen.toys.ipv6;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* @author qiubaisen
* @date 2020/7/23
*/
public class P {
int a;
long b;
String c;
public int getA() {
return a;
}
public long getB() {
return b;
}
public String getC() {
return c;
}
public P(int a, long b, String c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public String toString() {
return String.format("P{a=%d, b=%d, c='%s'}", a, b, c);
}
public static void main(String[] args) {
Comparator<P> congruent = (o1, o2) -> 0;
ThreadLocalRandom localRandom = ThreadLocalRandom.current();
Supplier<P> random = () -> new P(localRandom.nextInt(1,3), localRandom.nextLong(10,13),
new String(new char[]{(char) localRandom.nextInt('a', 'c')}));
List<P> origin = IntStream.range(0, 10).mapToObj(x -> random.get()).collect(Collectors.toList());
List<P> result = origin.stream().sorted(congruent.thenComparing(P::getA).thenComparing(P::getB)
.thenComparing(congruent.thenComparing(P::getC).reversed())
).collect(Collectors.toList());
System.out.println(origin);
System.out.println(result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment