-
案例需求:按照下面的要求完成集合的创建和遍历
-
创建一个集合,存储多个字符串元素
-
把集合中所有以"张"开头的元素存储到一个新的集合
-
把"张"开头的集合中的长度为3的元素存储到一个新的集合
-
遍历上一步得到的集合
public class StreamDemo { public static void main(String[] args) { //集合的批量添加 ArrayList<String> list1 = new ArrayList<>(List.of("张三丰","张无忌","张翠山","王二麻子","张良","谢广坤")); //Stream流 list1.stream().filter(s->s.startsWith("张")) .filter(s->s.length() == 3) .forEach(s-> System.out.println(s)); } }stream流有三种方法
-
获取方法、中间方法、终结方法
获取方法:获取stream流对象的方法
各种常见对象获取流的方法
- Collection体系集合:通过.stream()获得
- Map体系集合:先转成Set集合,再通过 .stream() 获得
- 数组对象:通过Arrays工具类获取,Arrays.stream(数组对象)获取
- 同种数据类型的多个数据:可以通过Stream.builder()先创建一个Stream对象再使用add方法将数据添加进stream流对象
Stream.Builder<Object> builder = Stream.builder(); //加入的必须是同类型对象 builder.add("a").add("b").add("c").add("d").build().forEach(System.out::println);
中间方法:Stream流对象的处理的方法
Stream<T> filter(Predicate predicate):过滤方法,里面写条件
ArrayList<String> list = new ArrayList<>();
list.add("张三丰");
list.add("张无忌");
list.add("张翠山");
list.add("王二麻子");
list.add("张良");
list.add("谢广坤");
Stream<String> stream = list.stream();
stream.filter(s -> s.startsWith("张")).forEach(System.out::println);
其他中间方法:
| Stream<T> limit(long maxSize) | 返回此流中的元素组成的流,拿到从前往后的指定数据个数 |
| Stream<T> skip(long n) | 跳过指定个数的数据,返回由该流的剩余元素组成的流 |
| static <T> Stream<T> concat(Stream a, Stream b) | 合并a和b两个流为一个流 |
| Stream<T> distinct() | 流元素去重(根据Object.equals(Object) ),拿到新流 |
| map方法 | 对流中每个元素进行操作Function |
| findFrist方法 | 拿到流对象的第一个元素 |
终结方法:每个stream流只有一个终结方法
常见的终结方法
| void forEach(Consumer action) | 对此流的每个元素执行操作 |
| long count() | 返回此流中的元素数 |
| orElse(值或者方法) | 如果stream流对象元素为空 |
收集方法:将流元素收集起来,比如放进莫集合中
| R collect(Collector collector) | 把结果收集到集合中,参数是工具类Collectors,返回值是对应类型集合 |
工具类Collectors常用方法
| public static <T> Collector toList() | 把元素收集到List集合中 |
| public static <T> Collector toSet() | 把元素收集到Set集合中 |
| public static Collector toMap(Function keyMapper,Function valueMapper) | 把元素收集到Map集合中 |
这里重点讲一下toMap方法
ArrayList<String> list = new ArrayList<>();
list.add("zhangsan,23");
list.add("lisi,24");
list.add("wangwu,25");
Map<String, String> map = list.stream()
.collect(Collectors.toMap(
s -> s.split(",")[0], //写一个function函数,指定什么值为键
s -> s.split(",")[1] //写一个function函数,指定什么值为值
));
System.out.println(map);
本文介绍了如何使用Java的StreamAPI来处理集合,包括创建集合、过滤以特定字符开头的元素、筛选长度为3的字符串,以及使用Stream的中间方法和终结方法。示例代码展示了如何通过filter和forEach方法遍历和打印集合,并演示了如何使用collect方法将流元素收集到Map中。
640

被折叠的 条评论
为什么被折叠?



