Skip to content

Instantly share code, notes, and snippets.

@jwgmeligmeyling
Created November 7, 2016 18:59
Show Gist options
  • Save jwgmeligmeyling/bec521357fba1b04a01dff4b1d1650a8 to your computer and use it in GitHub Desktop.
Save jwgmeligmeyling/bec521357fba1b04a01dff4b1d1650a8 to your computer and use it in GitHub Desktop.
Merge functions for solving duplicate keys in toMap collectors
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