3

i have a list with description of users like this:

0_Mary_Rose_maryrose@gmail.com
1_John_Smith_johnsmith@gmail.com

How can I order the list alphabetically?

I have this method:

protected List<String> ShowUsers() {                                   // show users list
    List<String> allUsersDesc = new ArrayList<>();                                                   // creates list for users description
    for (Map.Entry<Integer, User> user : _userMap.entrySet()) {                                        // scrolls users list
      allUsersDesc.add(user.getValue().getUserDescription());                                        // adds registered users
    }
    Collections.sort(allUsersDesc);                                                                  // sorts by description
    return allUsersDesc;                                                                             // return description list   }

and getUserDescription:

    public String getUserDescription(){
        String description = "" + getUserId() + "-" + getName() + "-" + getEmail() + "-" + getBehavior() + "-" + isActive();
        return description;
    }

But like this it is ordering by description and the first item of description is a number, so it is ordering by number and not by the users name.

  • 4
    Sort your List of users first. Once you have a sorted list of users, then transform it to a list of strings. – JB Nizet Nov 18 '19 at 14:31
  • Sort has a second argument for a comparator. You need a custom comparator, which sorts the entries the way you like it. E.g. by first extracting the user name with by using split("_")[1] or any other way. – Volokh Nov 18 '19 at 14:33
  • Use this: `list.sort((first, second) -> { final String firstPart = first.split("_")[1]; final String secondPart = second.split("_")[1]; return firstPart.compareTo(secondPart); });` – Nikolas Charalambidis Nov 18 '19 at 14:39
  • 1
    What if the e-mail-address also starts with a number? – tobias_k Nov 18 '19 at 14:40

2 Answers2

0

you can use the below code to remove integers and then compare the Strings

 Collections.sort(list, new Comparator<String>() {
            public int compare(String o1, String o2) {
                return removeInt(o1).compareTo(removeInt(o2));
            }
            String removeInt(String s) {
                String num = s.replaceAll("[0-9]+", "");
                return num;
            }
        });
dassum
  • 4,727
  • 2
  • 25
  • 38
-1
 allUsersDesc.sort(Comparator.comparing(desc -> desc.split("_")[1]));
jorne
  • 894
  • 2
  • 11
  • 23