-1

I have code like this:

final TreeMap<String, List<MyBean>> map= elements.stream()
                .filter(....)
                .collect(Collectors.groupingBy(MyBean::getName,
                        TreeMap::new,
                        Collectors.toList()
                ));

How to achieve that List is sorted by someStringField ?

pvpkiran
  • 23,183
  • 6
  • 71
  • 112
gstackoverflow
  • 34,819
  • 98
  • 304
  • 641

2 Answers2

2

You can add a Collectors#collectingAndThen to your Collectors#toList downstream:

final TreeMap<String, List<MyBean>> map = elements.stream()
      .collect(Collectors.groupingBy(MyBean::getName,
              TreeMap::new,
              Collectors.collectingAndThen(
                      Collectors.toList(),
                      l -> {
                          l.sort(Comparator.comparing(MyBean::getSomeStringField));
                          return l;
                      })
      ));
gstackoverflow
  • 34,819
  • 98
  • 304
  • 641
Flown
  • 11,142
  • 3
  • 42
  • 60
-1

I suggest you check the solution proposed in another thread: TreeMap sort by value

It seams you have to pass by SortedSet. TreeMap itself would not be sortable.