So, here comes answer from one perspective i.e. performance.
Here is my code I used to test it:-
AC class:-
package com.test;
public class AC {
private Long id;
public AC(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toString() {
return "AC{" +
"id=" + id +
'}';
}
}
Main class:-
package test.java;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
@org.openjdk.jmh.annotations.Benchmark
public void measureName() {
List<AC> acs = new ArrayList<>();
acs.add(new AC(20l));
acs.add(new AC(30l));
acs.add(new AC(10l));
acs.add(new AC(30l));
acs.add(new AC(80l));
acs.add(new AC(50l));
acs.add(new AC(30l));
acs.add(new AC(90l));
acs.add(new AC(80l));
acs.add(new AC(110l));
/* acs
.stream()
.sorted(Comparator.comparingLong(AC::getId)) //sorted by id here
.collect(Collectors.toList());*/
acs.stream()
.sorted((a, b) -> Long.compare(a.getId(), b.getId())) //sorted by id here
.collect(Collectors.toList());
}
public static void main(String[] args) {
Options opt = new OptionsBuilder()
.include(".*" + Main.class.getSimpleName() + ".*")
.forks(1)
.build();
try {
new Runner(opt).run();
} catch (RunnerException e) {
e.printStackTrace();
}
}
}
Putting below output using JMH for using Comparator.comparingLong
:-
# Run complete. Total time: 00:00:40
Benchmark Mode Cnt Score Error Units
Main.measureName thrpt 20 4130836.283 ± 86675.431 ops/s
and for Long.compare
below:-
# Run complete. Total time: 00:00:40
Benchmark Mode Cnt Score Error Units
Main.measureName thrpt 20 4106542.318 ± 146956.814 ops/s
If I go by these statistics Long.compare
is somehow faster though difference is very minor.
Please feel free to put in comments your findings if any and I would try those too.