How to do sorting in java if in a single variable name and number both are present

Vatsal Rahul :

I am doing a sorting thing so i am using java spring boot and i am using streams currently sorted by

sort code is :-

projectResponse.setDetails(v.stream()
                    .sorted(Comparator.comparing(StateResponse::getState)
                            .thenComparing(Comparator.comparing(NameResponse::getName)))
                    .collect(Collectors.toList()));

To sort first by state and then by name.

My name has value something like : "name-98","name-99","name-100" so when it is sorting it sorting correctly till 99 but when 100 comes it is the first sorted number and then sorting is correct from 100,101,102 and this situation will again come when the no will cross 999 and then sorting will be coming from 1000,1001 correctly . What is the best possible solution to overcome it ?

jspcal :

It's helpful to use a custom comparator that sorts the numbers in numerical order while at the same time sorting the text in alphabetic order. This is often referred to as "natural sort". Here's one implementation that does that: http://www.davekoelle.com/alphanum.html.

To use it in your stream operation:

thenComparing(NameResponse::getName, new AlphanumComparator())

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=102227&siteId=1