Created
March 20, 2016 16:09
-
-
Save nabbe/41036df946f639b2f9bf to your computer and use it in GitHub Desktop.
Mapの要素をフィルターするのってめんどくさいよね
This file contains hidden or 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 static org.hamcrest.MatcherAssert.assertThat; | |
import static org.hamcrest.Matchers.*; | |
import java.util.HashMap; | |
import java.util.Map; | |
import java.util.Set; | |
import java.util.stream.Stream; | |
import org.junit.Test; | |
public class Sandbox { | |
@Test | |
public void mapfilter() { | |
Map<String, Integer> map = new HashMap<>(); | |
map.put("a", 1); | |
map.put("b", 2); | |
map.put("c", 3); | |
Map<String, Integer> result = Stream.of(map) | |
.map(Map::entrySet) | |
.flatMap(Set::stream) | |
.filter(e -> (e.getValue() % 2) != 0) | |
.reduce( | |
new HashMap<String,Integer>(), | |
(m, e) -> {m.put(e.getKey(),e.getValue()); return m;}, | |
(a, b) -> {a.putAll(b); return a;} | |
); | |
assertThat(result, allOf(hasEntry("a", 1), not(hasEntry("b", 2)), hasEntry("c", 3))); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ぐれいつ