Java 8 Collectors.toMap SortedMap

I'm using Java 8 lambdas and want to use Collectors toMap to return a SortedMap. The best I can come up with is to call the following Collectors toMap method with a dummy mergeFunction and mapSupplier equal to TreeMap::new.

public static <T, K, U, M extends Map<K, U>> Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier) { BiConsumer<M, T> accumulator = (map, element) -> map.merge(keyMapper.apply(element), valueMapper.apply(element), mergeFunction); return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID); }

I don't want to pass in a merge function though, as I just want throwingMerger(), in the same way as the basic toMapimplementation as follows:

public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper) { return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new); }

What would be the best practise method of using Collectors to return a SortedMap?

-------------Problems Reply------------

I don't think you can get much better than this:

.collect(Collectors.toMap(keyMapper, valueMapper,
(k,v) ->{ throw new RuntimeException(String.format("Duplicate key %s", k));},
TreeMap::new));

where the throw lambda is the same as throwingMerger() but I can't directly call that since it's package private (you can of course always make your own static method for that like throwingMerger() is. )

Seems that there's no standard way to do this without defining your own throwingMerger() method or using explicit lambda. In my StreamEx library I defined the toSortedMap method which also uses my own throwingMerger().

Based on dkatzel's confirmation that there's not a nice API method, I've opted for maintaining my own custom Collectors class:

public final class StackOverflowExampleCollectors {

private StackOverflowExampleCollectors() {
throw new UnsupportedOperationException();
}

private static <T> BinaryOperator<T> throwingMerger() {
return (u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
};
}

public static <T, K, U, M extends Map<K, U>> Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper, Supplier<M> mapSupplier) {
return Collectors.toMap(keyMapper, valueMapper, throwingMerger(), mapSupplier);
}

}

Another way you can do this is to allow Collectors.toMap() to return whatever map it is going to return, and then pass that to a new TreeMap<>().

The caveat there is that this only works if your "hashCode()+equals()" and "compareTo" are consistent. If they aren't consistent, then you'll end up with the HashMap removing different set of keys than your TreeMap.

Category:java Views:17 Time:2019-02-07

Related post

  • Java: how to convert a List to a Map 2010-07-07

    I would like to find a way to take the object specific routine below and abstract it into a method that you can pass a class, list, and fieldname to get back a Map. If I could get a general pointer on the pattern used or , etc that could get me start

  • Is there a Java equivalent of Python's 'enumerate' function? 2011-08-23

    In Python, the enumerate function allows you to iterate over a sequence of (index, value) pairs. For example: >>> numbers = ["zero", "one", "two"] >>> for i, s in enumerate(numbers): ... print i, s ... 0 zero 1 one 2 two Is there an

  • Java map to flex object conversion 2011-07-04

    From java i am sending ordered Map.In flex when i convert that into Object i am loosing the order which i maintained in java.Is there any other way to maintain the order in flex object? Regards, Siva --------------Solutions------------- Java Maps (in

  • how to get specifics rows of 2d array returned by reading CSV file in java 2014-08-20

    This is data.csv file, now I want rows having classtype x (any number) and store those extarcted rows into new array, so if i have n classtype then i will have n new arrays. age sex zipcode classtype 21 m 23423 1 12 f 23133 2 23 m 32323 2 23 f 23211

  • Refactoring into Java 8 stream 2014-12-01

    i have method that viewed under message. I want refactored this method from "for each" to stream view like myCollect.stream().collect(Collectors.toMap(..))) but don't understand how it does work Collectors.toMap(..). private <T extends Entity>

  • TreeMap sort by value 2010-05-19

    I'm new to java, i want to write an comparator to that will let me sort TreeMap by value instead of the default natural sorting. i tried something like this, but can't find out what went wrong: import java.util.*; class treeMap { public static void m

  • Sorting HashMap by values 2011-11-14

    I need to sort my HashMap according to the values stored in it. The HashMap contains the contacts name stored in phone. Also I need that the keys get automatically sorted as soon as I sort the values, or you can say the keys and values are bound toge

  • How can I Initialize a static Map? 2009-02-03

    How would you initialise a static Map in Java? Method one: Static initializer Method two: instance initialiser (anonymous subclass) or some other method? What are the pros and cons of each? Here is an example illustrating two methods: import java.uti

  • Is there a smart way to check if for each key in a hash table, they all have the same value? 2015-01-19

    Is there a smart way to check if all keys map to the same value? So the hash table will be as below: a=>2; b=>2; c=>2; d=>2; So a,b,d,c and d all map to the same val. I am asking because I have to find the maximum occurrence of a number i

  • What signature for a generic method mapValues(map,mapper)? 2016-02-28

    I wrote a custom CollectionUtils class to compensate for the lack of certain important functional features in Java 8. However, I'm not really versed in complex genericity and I'm not sure of what signature to give to the following method : public sta

  • Programming language for functional parallelism: F# vs Haskell 2011-03-30

    Functional programming has immutable data structures and no side effect which are inherently suitable for parallel programming. I investigate how to exploit multicore computation in a functional language, and target production code for some numerical

  • Question about the Java Garbage Collector, nulls and memory leaking 2008-12-20

    Suppose I'm implementing a queue in java and I have a reference to the initial node, called ini and another to the last one, called last. Now, I start inserting objects into the queue. At one point, I decide I want an operation to clear the queue. Th

  • .Net vs Java Garbage Collector 2009-01-29

    Does anyone know the major differences between the Java and .Net garbage collectors? A web search has not revealed much, and it was a question that came up in a test. --------------Solutions------------- The difference is between the CLR (.Net) GC an

  • The best way to iterate SortedSet / SortedMap in Java backwards 2009-03-16

    I need to iterate through SortedMap's entry set (which is a SortedSet) backwards. The code I'm writing is extremely performance-sensitive, as it's going to be called from many places thousands times per second, maybe more. Any advice on doing it the

  • What does CMS mean in relation to Java's Garbage Collector? 2009-04-17

    A lot of JVM's command line arguments dealing with the garbage collector have "CMS" prepended to them. What does this stand for? --------------Solutions------------- Concurrent Mark Sweep (Or as Tom mentions in the comments, mostly Concurrent Mark Sw

  • Java garbage collector - When does it collect? 2009-10-17

    What is it that determines when the garbage collector actually collects? Does it happen after a certain time or after a certain amount of memory have been used up? Or are there other factors? --------------Solutions------------- It runs when it deter

  • Need java test cases to test MarkSweep Garbage collector 2009-11-27

    Can anyone provide me test cases in java in which objects are being incrementally created so that i can use those to test my MarkSweep garbage collection code. --------------Solutions------------- The Jikes RVM open source project has a complete suit

  • Java Collections and Garbage Collector 2010-01-18

    A little question regarding performance in a Java web app. Let's assume I have a List<Rubrique> listRubriques with ten Rubrique objects. A Rubrique contains one list of products (List<product> listProducts) and one list of clients (List

  • Can we have a customized Garbage collector in java? 2010-01-25

    As we know the java's garbage collector is a low priority thread. And in java we can create any thread with high priority. So is it possible to have our own customized garbage collector thread with variable priority (we can set depending on the level

  • Java SortedMap to Scala TreeMap 2010-01-29

    I'm having trouble converting a java SortedMap into a scala TreeMap. The SortedMap comes from deserialization and needs to be converted into a scala structure before being used. Some background, for the curious, is that the serialized structure is wr

  • logic of Garbage collector in java 2010-02-04

    As we know Garbage collector is Thread in java. And every thread will have its logic to execute. So i wanted to know what logic does this Garbage collector use which maintains the memory so well. thanks --------------Solutions------------- An object

  • Will Java's garbage collector interrupt a thread? 2010-03-10

    Something is interrupting threads in my application. It appears to happen when the JVM is close to running out of heap space. I can configure additional heap for the JVM but I'm curious if the garbage collector is interrupting threads in an attempt t

  • Why other languages don't have automatic garbage collection similar as that of the Java Garbage Collector? 2010-03-15

    What are the reason/s behind other languages not having a Garbage Collector? EDIT: Why garbage collection is not built-in for these other languages? why do programmers given the responsibility to collect? EDIT: All of the questions if possible please

  • How can I see which garbage collector java is using 2010-03-23

    The Java Virtual Machine supports several garbage collection strategies. This article explains them. Now I am wondering which (automatically selected) strategy my application is using, is there any way to let the JVM(version 1.6) print this informati

  • Create a SortedMap in Java with a custom Comparator 2010-05-01

    I want to create a TreeMap in Java with a custom sort order. The sorted keys which are string need to be sorted according to the second character. The values are also string. Sample map: Za,FOO Ab,Bar --------------Solutions------------- You can use

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.083 (s). 11 q(s)