0

I have a list of Object say Car. First I want to group the collection on some field say carCompanyId. So I will have something like,

Map<Integer, List<Car>> = cars.stream().collect(Collectors.groupingBy(Car::getCarCompanyId))

I want every list in above Map to be sorted by one of the fields. Can I achieve this by adding parameter to grouping by function so that it sorts the list while grouping it.

vaibhavvc1092
  • 3,067
  • 4
  • 19
  • 26
  • @tunaki This question is very different from the one you marked it as duplicate. – vaibhavvc1092 Apr 27 '16 at 09:10
  • No it is not, you want to sort a List according to one of its fields. Which is what the linked question answers in the general sense. – Tunaki Apr 27 '16 at 09:12
  • @tunaki : I want to group it and sort it simultaneously. – vaibhavvc1092 Apr 27 '16 at 09:14
  • 1
    You can use the downstream with `Collectors::toList` and a finisher function. `Map> map = cars.stream().collect(groupingBy(Car::getCarCompanyId, collectingAndThen(toList(), list -> { list.sort(comparingInt(Car::getCarMetric)); return list; })));` – Flown Apr 27 '16 at 09:39
  • 1
    @Flown: since `toList()` doesn’t guaranty to return a mutable list, you have to use `toCollection(ArrayList::new)` instead, if you want to sort it afterwards. Of course, it’s simpler to chain a `sorted(comparingInt(Car::getCarMetric))` before the `collect` operation… – Holger Apr 27 '16 at 10:06

0 Answers0