今天写根过滤的时候一下子有点愣眼,先是想到用 Java 原生的 map 循环查出来,但是觉得太 low, 后面思考了一下可以用 Java8 的 Lambda,写完了,又发现 Google Guava 有现成的方法,这里一一列出来,供参考使用。
首先提示,如果照搬我的代码的话别忘了引这些依赖
junitjunit4.12testorg.hamcresthamcrest-coreorg.hamcresthamcrest-library1.3testcom.google.guavaguava25.1-jre
filter by key
publicclassFilterMapByKeyTest{privateMap WEEK =newHashMap<>();@BeforepublicvoidsetUp(){ WEEK.put(1,"Monday"); WEEK.put(2,"Tuesday"); WEEK.put(3,"Wednesday"); WEEK.put(4,"Thursday"); WEEK.put(5,"Friday"); WEEK.put(6,"Saturday"); WEEK.put(7,"Sunday"); }/**
* Java 8之前的版本
*/@TestpublicvoidfilterMapByKey(){ Map map =newHashMap<>();for(Map.Entry entry : WEEK.entrySet()) {if(entry.getKey() <=3) { map.put(entry.getKey(), entry.getValue()); } } assertThat(map.keySet(), contains(1,2,3)); }/**
* Java 8 Lambda
*/@TestpublicvoidfilterMapByKeyJava8Lambda(){ Map map = WEEK.entrySet().stream().filter(r -> r.getKey() <=3) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); assertThat(map.keySet(), contains(1,2,3)); }/**
* Google Guava
*/@TestpublicvoidfilterMapByKeyGuava(){ Map map = Maps.filterKeys(WEEK, r -> r <=3); assertThat(map.keySet(), contains(1,2,3)); }}
filter by value
publicclassFilterMapByValueTest{privateMap WEEK =newHashMap<>();@BeforepublicvoidsetUp(){ WEEK.put(1,"Monday"); WEEK.put(2,"Tuesday"); WEEK.put(3,"Wednesday"); WEEK.put(4,"Thursday"); WEEK.put(5,"Friday"); WEEK.put(6,"Saturday"); WEEK.put(7,"Sunday"); }/**
* Java 8之前的版本
*/@TestpublicvoidfilterMapByValue(){ Map map =newHashMap<>();for(Map.Entry entry : WEEK.entrySet()) {if(entry.getValue().startsWith("S")) { map.put(entry.getKey(), entry.getValue()); } } assertThat(map.values(), contains("Saturday","Sunday")); }/**
* Java 8 Lambda
*/@TestpublicvoidfilterMapByValueJava8Lambda(){ Map map = WEEK.entrySet().stream().filter(r -> r.getValue().startsWith("S")) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); assertThat(map.values(), contains("Saturday","Sunday")); }/**
* Google Guava
*/@TestpublicvoidfilterMapByValueGuava(){ Map map = Maps.filterValues(WEEK, r -> r.startsWith("S")); assertThat(map.values(), contains("Saturday","Sunday")); }}
如果觉得内容还不错,可以关注一下我哦
网友评论