Reputation: 581
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
Reputation: 56423
Specify the sort key i.e:
List<Unit> sortedList = yards.stream()
.sorted(Comparator.comparing(e -> e.getName()))
.collect(Collectors.toList());
Upvotes: 2