【记录】【java】JDK8新特性Stream⽅式遍历集合由于是以流⽅式,所以怎么操作也不改变原来的集合
1、普通遍历forEach
List<String> list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
List<String> list2 = new ArrayList();
list.stream().forEach(str ->{
list2.add(str);
});
System.out.println(list2);
2、过滤filter
List<String> list = new ArrayList();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
List<String> list3 = new ArrayList();
// 过滤字符串为a的元素
list.stream().filter(str -> !"a".equals(str)).forEach(str -> {    list3.add(str);
});
System.out.println(list3);
3、排序sorted
List<String> list = new ArrayList();
list.add("ab");
list.add("aa");
list.add("c");
list.add("d");
System.out.println("操作前list: " + list);
List<String> collect = list.stream().sorted((a, b) -> { return apareTo(b);
}).List());
System.out.println("升序collect: " + collect);
java stream
List<String> collect2 = list.stream().sorted((a, b) -> { return bpareTo(a);
}).List());
System.out.println("降序collect2: " + collect2);
}
4、操作字符串集合,返回拼接字符串。collect的Collectors.joining List<String> list = new ArrayList();
list.add("b");
list.add("a");
list.add("c");
list.add("d");
System.out.println("操作前list: " + list);
String collect = list.stream().sorted((a, b) -> {
return bpareTo(a);
}).collect(Collectors.joining(",", "前", "后"));
System.out.println("有前后collect: " + collect);
String collect2 = list.stream().sorted((a, b) -> {
return bpareTo(a);
}).collect(Collectors.joining(","));
System.out.println("没前后collect: " + collect2);
5、操作map集合
List<Map<String, Object>> list = new ArrayList();
Map<String, Object> map = new HashMap<>();
map.put("id", "wwww");
list.add(map);
Map<String, Object> map2 = new HashMap<>();
map2.put("id", "qqqq");
list.add(map2);
Map<String, Object> map3 = new HashMap<>();
map3.put("name", "qqqq");
list.add(map3);
System.out.println("list: " + list);
String collect = list.stream().filter(map1 -> null != ("id"))        .map(str -> ("id").toString())
.collect(Collectors.joining(",", "前", "后"));
System.out.println("collect: " + collect);
6、操作对象
List<Student> list = new ArrayList();
Student student = new Student();
student.setAge("11");
student.setName("aaa");
list.add(student);
Student student2 = new Student();
student2.setAge("22");
student2.setName("bbb");
list.add(student2);
System.out.println("list: " + list);
String collect = list.stream().map(student3 -> Name())        .collect(Collectors.joining(",", "前", "后"));
System.out.println("collect: " + collect);
7、合并两个字符串数组flatMap
List<String[]> list = new ArrayList();
list.add(new String[]{"aa", "bb"});
list.add(new String[]{"ff", "ee"});
System.out.println("list: " + list);
String collect = list.stream().flatMap(Arrays::stream)        .collect(Collectors.joining(",", "前", "后"));
System.out.println("collect: " + collect);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。