Skip to content

Instantly share code, notes, and snippets.

@nabbe
Created March 20, 2016 16:09
Show Gist options
  • Save nabbe/41036df946f639b2f9bf to your computer and use it in GitHub Desktop.
Save nabbe/41036df946f639b2f9bf to your computer and use it in GitHub Desktop.
Mapの要素をフィルターするのってめんどくさいよね
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)));
}
}
@A-pZ
Copy link

A-pZ commented Mar 20, 2016

ぐれいつ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment