JAVA基础——Stream的用法

Stream不是流,而是对集合的一种增强。

如何创建一个Stream

package classwork;
//如何创建一个Stream
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
//stream对象
public class s1 {
	public static void main(String[] args) {
		Integer [] arr= {1,2,3,4,5,6};
		//方法1.数组
		//创建Stream对象
		//数组中的Stream方法;static直接类名调用
		Stream<Integer> stream1=Arrays.stream(arr);

		//方法2:of方法
		Stream<String> stream2=Stream.of("a","b","c");
		Stream<Integer> stream3=Stream.of(5,6,7,8);
		
		//方法3:创建一个集合
		List <Integer> list =Arrays.asList(10,11,12);
		//普通流
		Stream <Integer> stream001=list.stream();
		//并行流(多线程)
		Stream <Integer> stream002=list.parallelStream();
		
	}

}
                                                                                                                                                                                                                                                                               

stream过滤方法

package classwork;

import java.util.Arrays;
import java.util.stream.Stream;

//stream过滤方法
public class ss1 {

	public static void main(String[] args) {
		//保留数组中的偶数
		Integer [] arr= {1,2,3,4,5,6};
		Stream <Integer> stream = Stream.of(arr);
		Integer[] arr2=stream.filter(t->t%2==0).toArray(Integer[]::new);
		System.out.println(Arrays.toString(arr2));
		//简约版方法
		System.out.println(Arrays.toString(Stream.of(arr).filter(t->t%2==0).toArray(Integer[]::new)));

	}

}

distinct:去掉重复的元素

package classwork;

import java.util.stream.Stream;

public class ss2 {

	public static void main(String[] args) {
		Stream<Integer> stream2=Stream.of(1,1,1,2,3);
		//distinct:去掉重复的元素
		Stream<Integer> stream3=stream2.distinct();
		stream3.forEach(System.out::println);
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值