fwend
fwend

Reputation: 1853

How to specify a Comparator for a MapFactory

I have the following code that works correctly:

    Map<String, List<String>> map = Arrays.stream(input)
            .collect(groupingBy(s -> s.split("\\s+")[0],
                    TreeMap::new, toList()));

But I need the TreeMap to sort in descending order. I've tried:

    Map<String, List<String>> map = Arrays.stream(input)
            .collect(groupingBy(s -> s.split("\\s+")[0],
                    new TreeMap<>((a, b) -> b.compareTo(a)), toList()));

But I get the error "Cannot find symbol compare to object".

How do I get the TreeMap to accept a Comparator? Is it possible at all?

Upvotes: 1

Views: 491

Answers (3)

Alex - GlassEditor.com
Alex - GlassEditor.com

Reputation: 15507

It takes a Supplier<Map>, which you can make with a lambda like this:

() -> new TreeMap<>((a, b) -> b.compareTo(a))

also since you just want to reverse the order, you could use the method for that provided in the Comparator class:

() -> new TreeMap<>(Comparator.reverseOrder())

Upvotes: 2

Loganathan Mohanraj
Loganathan Mohanraj

Reputation: 1874

You have to pass the comparator to tree map as below only then it will store the values in some order as per the implementation of the comparator. The below code will allow you to store the values in a descending order.

TreeMap<String, String> treeMap = new TreeMap<String, String>(new Comparator<String>() {
    public int compare(String string1, String string2) {
    if (string1.compareTo(string2) > 0) {
        return -1;
    } else if (string1.compareTo(string2) < 0) {
        return 1;
    } else {
        return 0;
    }
    };
});

The other alternative way is to get the key in descending order using the below API from TreeMap and then retrieve the value from it.

Set<String> keySet = treeMap.descendingKeySet();
for (String key : keySet) {
    System.out.println(treeMap.get(key));
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

There may well be another way to do it, but I got it working with

String[] input = { "a", "b", "c" };
Map<String, List<String>> map = new TreeMap<>((a, b) -> b.compareTo(a));
map.putAll(Arrays.stream(input).collect(
    groupingBy(s -> s.split("\\s+")[0], TreeMap::new, toList())));
System.out.println(map);

Output is

{c=[c], b=[b], a=[a]}

Upvotes: 0

Related Questions