0

I have a list of Strings with two characters and want to sort by first character ascending and second character descending, for example "S1", "T1", "T2" should be sorted to "S1", "T2", "T1".

Seemed simple enough:

strings.sort(Comparator.comparing(code -> code.substring(0,1))
        .thenComparing(code -> code.substring(1,2).reversed()));

After typing out the first part

strings.sort(Comparator.comparing(code -> code.substring(0,1))

Anything is still okay, autocomplete tells me about substring (Intellij), but when I add

.thenComparing(code -> code.substring(1,2).reversed()));

Somehow Java doesn't know anymore that it's working with Strings and gives me the error

Cannot resolve method 'substring' in 'Object'

for the .substring method calls on both.

Same happens when using stream().sorted()

enter image description here

Bernhard
  • 1,257
  • 9
  • 18
  • You are trying to reverse the substring instead of the sorted list. String doesn't have a `reversed`method – jhamon Jan 07 '20 at 15:44
  • Instead of screenshots please add code snippets. – Boris Jan 07 '20 at 15:44
  • 2
    [Comparator.reversed() does not compile using lambda](https://stackoverflow.com/q/25172595). Use explicit type here like `(String code) -> ...` – Pshemo Jan 07 '20 at 15:44
  • 2
    If you add the type witness, it works `Comparator.comparing(code -> code.substring(0,1)).thenComparing(code -> code.substring(1,2))`. There is not a `String::reversed` method, and your string is 1 character long, so I don't know what you were doing there – Michael Jan 07 '20 at 15:45
  • @jhamon yes the reverse was misplaced but it was not causing the issue, just a quick typo on the example code – Bernhard Jan 07 '20 at 15:49
  • 2
    @Boris The Code snippets are all there, the image was just to illustrate where the error occurs, I'd never post a code screenshot without code snippets – Bernhard Jan 07 '20 at 15:50
  • BTW be sure what you are reversing. When you have `Comparator.comparing(..ord1..).thenComparing(..ord2..)` it creates **ord1,ord2**. But if you add `.reversed()` at the end it will reverse *entire ordering* like **rev(ord1,ord2)** resulting in **rev(ord1),rev(ord2)**. If you want to achieve **ord1,rev(ord2)** you should use `.thenComparing(Comparator.comparing(..ord2..).reversed())` instead of `thenComparing(..ord2..).reversed()`. Notice that reversing applies only to comparator in `thenComparing(...)`. – Pshemo Jan 07 '20 at 16:05

0 Answers0