Samarland
Samarland

Reputation: 581

Java Sorting list alpha

I'm trying to sort the list alphabetically Unit class has: name and number. I'm trying to sort by name.

using my code it's sorted but not alphabetically. My code is: (tried both the commented and the not commented one.

List<Unit> yards = new ArrayList<>(unitsApi.getAllUnits());

Collections.sort(yards, new BeanComparator<Unit>("name"));

//another try
    List<Unit> sortedNames = yards.stream().sorted().collect(Collectors.toList());

//num3 another
            //List<Unit> sortedList = yards
                 .stream().sorted(Comparator.comparing(Object::toString))
                .collect(Collectors.toList());

    model.addAttribute("yards", sortedList);

Upvotes: 0

Views: 81

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56423

Specify the sort key i.e:

List<Unit> sortedList = yards.stream()
                             .sorted(Comparator.comparing(e -> e.getName()))
                             .collect(Collectors.toList());

Upvotes: 2

Related Questions