Search code examples
group-bytreemapkotlin

Kotlin sortBy on TreeMap


What is the kotlin way of accomplisg this:

public static TreeMap<Integer, ArrayList<HomeItem>> getHomeItemListsSeparatedByPageId(List<HomeItem> homeItemsList) {

        if (homeItemsList.size() == 0) {
            return new TreeMap<>();
        }

        TreeMap<Integer, ArrayList<HomeItem>> map = new TreeMap<>();

        for (HomeItem hl : homeItemsList) {
            if (map.get(hl.getVisiblePageId()) == null) {
                map.put(hl.getVisiblePageId(), new ArrayList<>());
            }
            map.get(hl.getVisiblePageId()).add(hl);
        }

        return map;
    }

I have tried to apply groupBy on my args list but it returns an HashMap.

EDIT: Basically, the original list is queried, and it is grouped by visiblePageId, and added to a treemap whose key is the id and the value are the items with that id


Solution

  • You can use the groupByTo method and pass a TreeMap instance as the first argument.

    fun getHomeItemListsSeparatedByPageId(homeItems: List<HomeItem>) =
        homeItems.groupByTo(TreeMap()) { it.visiblePageId }