-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
  • 25,582
  • 8
  • 87
  • 134
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

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
  • 36,709
  • 117
  • 359
  • 710
Flown
  • 11,480
  • 3
  • 45
  • 62
-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.