Created
November 7, 2016 18:59
-
-
Save jwgmeligmeyling/bec521357fba1b04a01dff4b1d1650a8 to your computer and use it in GitHub Desktop.
Merge functions for solving duplicate keys in toMap collectors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package nl.meylingmedia.util; | |
import java.util.Comparator; | |
import java.util.function.BinaryOperator; | |
import java.util.function.Function; | |
/** | |
* Merge functions for solving duplicate keys in toMap collectors. | |
* | |
* @see java.util.stream.Collectors#toMap(Function, Function, BinaryOperator) | |
* @author Jan-Willem Gmelig Meyling | |
*/ | |
public class MergeUtil { | |
public static <T> BinaryOperator<T> usingInitialValue() { | |
return (a,b) -> a; | |
} | |
public static <T> BinaryOperator<T> usingLastValue() { | |
return (a,b) -> b; | |
} | |
public static <T> BinaryOperator<T> usingMaxValue(Comparator<T> comparator) { | |
return (a,b) -> comparator.compare(a, b) >= 0 ? a : b; | |
} | |
public static <T extends Comparable<T>> BinaryOperator<T> usingMaxValue() { | |
return usingMaxValue(Comparator.<T> naturalOrder()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment