简体   繁体   中英

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

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()));

I have also had these problems a couple of times, especially with Comparator. Eclipse and/or the java compiler have trouble infering the types correctly . As Holger pointed out, this is not a bug but working as specified: The types in the Comparator cannot be inferred solely by the expected type of sorted 's parameter. You have to type manually/explicitly to give it enough info to compile:

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

In the subsequent thenComparing s the type is then correctly recognized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM