List<ObjectComposition> objComposition = objectsComposition.stream() .sorted((oc1, oc2) -> { return Integer.parseInt(oc1.getNumberAccordingToPlan().replaceAll("\\D+", "")) - Integer.parseInt(oc2.getNumberAccordingToPlan().replaceAll("\\D+", "")); }) .sorted((oc1, oc2) -> { return Integer.parseInt(oc1.getGroupNumber().replaceAll("\\D+", "")) - Integer.parseInt(oc2.getGroupNumber().replaceAll("\\D+", "")); }) .collect(Collectors.toList()); 

Well, it should be sorted normally - by number and by group. What would be the group values ​​in ascending order. It turns out:
enter image description here
Don't understand what I'm doing wrong?

  • numberAccordingToPlan problem reproduced when sorting only by numberAccordingToPlan ? On two sites? If so, can you prepare a reproducible example ? - default locale

1 answer 1

Your stream to this location inclusive will be sorted by numberAccordingToPlan

 objectsComposition.stream() .sorted((oc1, oc2) -> { return Integer.parseInt(oc1.getNumberAccordingToPlan().replaceAll("\\D+", "")) - Integer.parseInt(oc2.getNumberAccordingToPlan().replaceAll("\\D+", "")); }) ... ... 

and from this:

 ... ... .sorted((oc1, oc2) -> { return Integer.parseInt(oc1.getGroupNumber().replaceAll("\\D+", "")) - Integer.parseInt(oc2.getGroupNumber().replaceAll("\\D+", "")); }) 

it will be sorted by groupNumber only

To achieve what you need, you need to use one comparator:

 List<ObjectComposition> objComposition = objectsComposition.stream() .sorted((oc1, oc2) -> { int cmp = Integer.parseInt(oc1.getNumberAccordingToPlan().replaceAll("\\D+", "")) - Integer.parseInt(oc2.getNumberAccordingToPlan().replaceAll("\\D+", "")); if(cmp == 0){ cmp = Integer.parseInt(oc1.getGroupNumber().replaceAll("\\D+", "")) - Integer.parseInt(oc2.getGroupNumber().replaceAll("\\D+", "")); } return cmp; }) .collect(Collectors.toList()); 

If you need the groupNumber field groupNumber first sort key, change the comparison order in this comparator.

  • Does not help. The problem is the same as in the picture - 1 is at the end of the B-1 group ... - Artem -.... .- ....-.-
  • one
    @Artyom, there can be no such thing. You did something wrong. Why do you have groundType output in groundType , and groupNumber in code? It is the same? - iksuy
  • one
    Hand face. My fault. I do not understand how I did not notice. Yes, these are different fields. Thank. ZY Sorting .sorted ((oc1, oc2) -> {...}). Sorted ((oc1, oc2) -> {...}) sorts correctly. - Artyom ... .- ....-.-
  • one
    @ Artem -.....-...-.-, if the answer helped you, then you can mark it true) - YuriySPb
  • one
    @ Artem, yes, everything really works correctly, I already understood :) - iksuy