Stream流

Stream流

stream ➡ 中间方法 ➡ 终结方法

Stream流的获取
  • 单列集合:集合对象,stream();
  • 双列集合:
    • 不能直接获取,需要间接获取
      • 集合对象.keyset().stream();
      • 集合对象.entryset().stream()
  • 数组
    • Arrays.stream(数组名);
  • 同种数据类型的多个数据:
    • Stream.of(数据1,数据2,数据3…;
ArrayList<String> list = new ArrayList<>();
list.stream()...;

HashMap<String,Integer> hm = new HashMap<>();
hm.keySet().stream().forEach(s->System.out.println(s)); // 键
hm.entrySet().stream().forEach(s->System.out.println(s)); // 键值对

int[]arr={1,2,3,4,5};
Arrays.stream(arr).forEach(s->System.out.println(s));

Stream.of(1,2,3,4,5,6,7,8).forEach(s->system.out.printIn(s));
中间方法
filter

过滤数据 startsWith(),以什么开头

ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().filter(f->f.startsWith("x")).forEach(System.out::println); // xl xxl
limit

截取前面的数据

ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().limit(1).forEach(System.out::println); // lx
skip

截取后面的数据

ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().skip(1).forEach(System.out::println); // xl xxl
concat

合并两个流成为一个流

ArrayList<String> list1 = new ArrayList<>(List.of("lx","xl","xxl"));
ArrayList<String> list2 = new ArrayList<>(List.of("lx","xl","xxl"));
Stream.concat(list1,list2).forEach(System.out::println);
distinct

去重,依赖hashCode和equals方法

ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().distinct().forEach(System.out::println);
终结方法

终结方法和收集方法只能有一个。不可以同时存在

forEach

对每个元素进行操作

ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().forEach(System.out::println); // lx xl xxl
count

返回的是流中的元素的个数

ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().count(); // 3
收集方法

stream流是不可以直接修改源数据的,需要用到其他的方法

collect

收集最后的结果,只管收集,不管其他

ArrayList<String> list = new ArrayList<>(List.of("lx","xl","xxl"));
list.stream().filter(f->f.startsWith("x")).collect(); // xl xxl

收集之后需要用方法来创建容器,方法都有返回值

Collectors.toList()

创建一个List容器

List<String> l = list.stream().filter(f->f.startsWith("x")).collect(Collectors.ToList()); // xl xxl

List<String> l = list.stream().filter(f->f.startsWith("x")).toList();
Collectors.toSet()

创建一个Set容器

Collectors.toMap()

创建一个Map容器

ArrayList<String> list = new ArrayList<>();
list.add("zhangsan,23");
list.add("lisi,24");
list.add("wangwu,25");

Map<String,Integer> map = list.stream().collect(Collectors.toMap(
	m -> m.split(",")[0],
    m -> Integer.parseInt(m.split(",")[1]),
))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值