Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Stream Sort - Comparator with 2 or more Criteria for Objects

Issue: I am trying to check if I can sort the list (ArrayList of data type Object), using 2 or more criteria's. Please note I am aware of using Comparator with thenComparing feature. I wish to check if there is a way to sort with 2 or more criteria w/o having to use a custom data type where I can easily use Comparator feature. For 1 criteria sorting, the below code works.

In this case if I do the below, the IntelliJ IDE immediately gives a error saying - 'Cannot resolve method 'get(int)' for o.get(3)

.sorted(Comparator.comparing(o -> o.get(3).toString()).thenComparing(...)

I have also referred to many threads in this forum sample - Link1 Link2

Code (This works well for single criteria)

List<List<Object>> listOutput = new ArrayList<>();
.........
.........
listOutput = listOutput
                    .stream()
                    .sorted(Comparator.comparing(o -> o.get(3).toString()))
                    .collect(Collectors.toList());

Added (Details of Object)

(Note)

String dataType - exchange, broker,segment, coCode

LocalDate dataType - tradeDate

LocalTime dataType - tradeTime

double dataType - sellPrice, buyPrice

List<Object> lineOutput = new ArrayList<>();
lineOutput.add(exchange);
lineOutput.add(broker);
lineOutput.add(segment);
lineOutput.add(tradeDate);  // Entry Date
lineOutput.add(tradeTime);   // Entry Time
lineOutput.add(coCode);
lineOutput.add(sellPrice - buyPrice);   // Profit / Loss 
listOutput.add(lineOutput); // Add line to Output
like image 875
iCoder Avatar asked Feb 13 '26 23:02

iCoder


1 Answers

It seems that the compiler can not infer the correct types (I've tried javac 8 and 9 with the same effect). The only way I could make it work is specifying the types directly via casting:

list.stream()
    .sorted(
       Comparator.comparing((List<Object> o) -> o.get(3).toString())
                 .thenComparing((List<Object> x) ->  x.get(3).toString()));
like image 142
Eugene Avatar answered Feb 16 '26 11:02

Eugene