Java Map 通过 key 或者 value 过滤的实例代码
今天写根过滤的时候一下子有点愣眼,先是想到用Java原生的map循环查出来,但是觉得太low,后面思考了一下可以用Java8的Lambda,写完了,又发现GoogleGuava有现成的方法,这里一一列出来,供参考使用。
首先提示,如果照搬我的代码的话别忘了引这些依赖
junit junit 4.12 test org.hamcrest hamcrest-core org.hamcrest hamcrest-library 1.3 test com.google.guava guava 25.1-jre
filterbykey
publicclassFilterMapByKeyTest{
privateMapWEEK=newHashMap<>();
@Before
publicvoidsetUp(){
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");
}
/**
*Java8之前的版本
*/
@Test
publicvoidfilterMapByKey(){
Mapmap=newHashMap<>();
for(Map.Entryentry:WEEK.entrySet()){
if(entry.getKey()<=3){
map.put(entry.getKey(),entry.getValue());
}
}
assertThat(map.keySet(),contains(1,2,3));
}
/**
*Java8Lambda
*/
@Test
publicvoidfilterMapByKeyJava8Lambda(){
Mapmap=WEEK.entrySet().stream().filter(r->r.getKey()<=3)
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
assertThat(map.keySet(),contains(1,2,3));
}
/**
*GoogleGuava
*/
@Test
publicvoidfilterMapByKeyGuava(){
Mapmap=Maps.filterKeys(WEEK,r->r<=3);
assertThat(map.keySet(),contains(1,2,3));
}
}
filterbyvalue
publicclassFilterMapByValueTest{
privateMapWEEK=newHashMap<>();
@Before
publicvoidsetUp(){
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");
}
/**
*Java8之前的版本
*/
@Test
publicvoidfilterMapByValue(){
Mapmap=newHashMap<>();
for(Map.Entryentry:WEEK.entrySet()){
if(entry.getValue().startsWith("S")){
map.put(entry.getKey(),entry.getValue());
}
}
assertThat(map.values(),contains("Saturday","Sunday"));
}
/**
*Java8Lambda
*/
@Test
publicvoidfilterMapByValueJava8Lambda(){
Mapmap=WEEK.entrySet().stream().filter(r->r.getValue().startsWith("S"))
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
assertThat(map.values(),contains("Saturday","Sunday"));
}
/**
*GoogleGuava
*/
@Test
publicvoidfilterMapByValueGuava(){
Mapmap=Maps.filterValues(WEEK,r->r.startsWith("S"));
assertThat(map.values(),contains("Saturday","Sunday"));
}
}
总结
以上所述是小编给大家介绍的JavaMap通过key或者value过滤的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。