一、List操作
List<String> list = new ArrayList<>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
list.add("eee");
//1.遍历list
list.forEach(str->System.out.println(str));
//2.筛选出某一项,进行操作
list.forEach(str->{
if("aaa".equals(str)){
System.out.println(str);
//进行业务操作...
}
});
//3.使用Stream,将源list过滤掉某些元素。
list.stream().filter(s -> {
return s.contains("aaa");
}).collect(Collectors.toList());//只保留list中包含aaa的元素,其他元素被从list中过滤掉了。.collect代表使用流式操作之后,在给它收束回去,保证和源list类型一致。
//3.1使用Stream,将源list过滤掉某些元素,然后改变list中的元素
list.stream().filter(s -> {
return s.contains("aaa");
}).map(item -> {
item.substring(item.length() - 1);//将值截取一下,改变原来的值
return item;
}).collect(Collectors.toList());
//3.2上面3.1的内容可以应用在给实体类的list设置值,例如:
List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
return categoryEntity.getParentCid().equals(root.getCatId());//阿里巴巴开发手册建议:包装类比较应该使用equals方法
}).map(categoryEntity -> {
categoryEntity.setChildren(getChildren(categoryEntity,all));
return categoryEntity;
}).sorted((menu1,menu2)->{
return (menu1.getSort()==null?0:menu1.getSort()) - (menu2.getSort()==null?0:menu2.getSort());
}).collect(Collectors.toList());
总结:Stream中的map:设置值,处理元素。filter:过滤元素。
二、Map操作
Map<String, Integer> items = new HashMap<>();
items.put("a", 1);
items.put("b", 2);
items.put("c", 3);
items.put("d", 4);
items.put("e", 5);
items.put("f", 6);
//遍历
items.forEach((k,v)->System.out.println("key:" + k + "---value:" + v));
//遍历及删除
Iterator<Map.Entry<String, Integer>> iterator = items.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
if ("a".equals(entry.getKey())) {
iterator.remove();
}else{
System.out.println("key:" + entry.getKey() + "---value:" + entry.getValue());
}
}