StreamAPI和λ表达式在Map集合中的妙用
最近学习了StreamAPI、λ表达式,它们在Map集合中的应用真的是十分方便(排序、筛选、收集、遍历等),下面分享一个例子:
代码:
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class TestMap {
public static void main(String[] args) {
Map<String,Object> map = new HashMap<>();
map.put("html", "HyperText Markup Language");
map.put("css", "Cascding Style Sheets");
map.put("js", "JavaScript");
map.put("bs", "Bootstrap");
map.put("ssh", "Spring Struts2 Hibernate");
map.put("ssm", "Spring SpringMVC Mybatis");
map.put("xml", "Extension Markup Language");
map.entrySet().stream() //获取流
.filter(e -> e.getKey().toLowerCase().contains("s")) //筛选键中含“S”的元素
.sorted((e1,e2) -> e1.getValue().toString().length() - e2.getValue().toString().length()) //根据值的长度对元素排序
.filter(e -> e.getKey().length() >= 3) //筛选键长度大于等于3的元素
.skip(1) //跳过第一个元素
.limit(2) //截取两个元素
.map(e -> e.getValue()) //获取值集合
.collect(Collectors.toList()) //收集在List集合中
.forEach(System.out::println); //遍历
}
}
运行结果:
Spring Struts2 Hibernate
Spring SpringMVC Mybatis