Last active
August 21, 2019 22:30
-
-
Save Bill/633b180ce9a983922e3b21407101b1f7 to your computer and use it in GitHub Desktop.
one way to intersect sets
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
import java.util.HashSet; | |
import java.util.Set; | |
import java.util.function.Consumer; | |
class Scratch { | |
public static void main(String[] args) { | |
final Set<Integer> a = Set.of(1, 2, 3); | |
final Set<Integer> b = Set.of(3, 4, 5); | |
System.out.println("intersection: " + intersect(a, b)); | |
} | |
static <T> Set<T> intersect(final Set<T> a, final Set<T> b) { | |
return returning(new HashSet<T>(a), copy -> copy.retainAll(b)); | |
} | |
/** | |
* Return {@param val} after invoking {@param f} for side-effects. | |
* @param val is the value to return | |
* @param f is invoked for side-effects | |
* @param <T> is any class | |
* @return {@param val} | |
*/ | |
public static <T> T returning(final T val, final Consumer<T> f) { | |
f.accept(val); | |
return val; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment