JAVA小白的崛起之路(十一)Stream

JAVA小白的崛起之路(十一)Stream

Stream的操作三个步骤

1、创建Stream
一个数据源(如:集合、数组),获取一个流
2、中间操作
一个中间操作链,对数据源的数据进行处理
3、终止操作
一个终止操作,执行中间操作链,并产生结果

Stream
集合|数组->数据源,侧重与数据的存储
Stream对数据的计算,是对数据操作的元素序列

特点:
1.Stream不能存储数据
2.stream操作不影响数据源,得到一个新的stream
3.stream一次性的流,已经使用过后的流不能再次使用了,每次使用返回一个新的流
4.惰性加载|延迟执行

/*** StreamAPI三个操作步骤: 
* 1、创建Stream 
* 2、中间操作 
* 3、终止操作 
*/ 
public class TestStreamAPI1 { 
    // 创建Stream
    public void test1() { 
        // 1、可以通过Conllection系列集合提供的顺序流stream()或并行流 
        parallelStream() List<String> list = new ArrayList<>(); 
        Stream<String> stream1 = list.stream(); 
        stream1 = list.parallelStream(); 
        // 2、通过Arrays中的静态方法stream()获取数据流 
        Integer ints[] = new Integer[10]; 
        Stream<Integer> stream2 = Arrays.stream(ints); 
        // 3、通过Stream类中的静态方法of() 
        Stream<String> stream3 = Stream.of("aa", "bb", "cc");
        String str[] = new String[10]; 
        Stream<String> stream4 = Stream.of(str);
    }
}
中间操作:

​ 筛选和切片

​ **filter:**接收Lambda,从流中排除某些元素

Stream<Employee> stream = list.stream();
        //2.中间 操作
Stream<Employee> s = stream.filter(e->{
	System.out.println("-----------------过滤1----------------------");
	return e.getAge()<=35;
	});

​ **limit:**截断流,使其元素不超过给定数量

emps.stream()
.filter((e) -> e.getSalary() > 5000) //lambda表达式
.limit(2)        
.forEach(System.out::println); 


​ **skip:**跳过元素,返回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流。

 emps.stream()        
 .filter((e) -> e.getSalary() > 5000)        
 .skip(2)        
 .forEach(System.out::println); 

​ **distinct:**筛选,通过流所生产元素的hashCode()和equals()去除重复元素

 emps.stream()        
 .filter((e) -> e.getSalary() > 5000)        
 .distinct()        
 .forEach(System.out::println); 

sorted(Comparable)-自然排序

List<String> list = Arrays.asList("cc", "aa", "bb", "ee", "dd");
 
    list.stream()        
    .sorted()        
    .forEach(System.out::println); 

sorted(Comparator)-定制排序

emps.stream() 
    //重写比较器  
    .sorted((e1, e2) -> { 
        if(e1.getAge().equals(e2.getAge())) {
            return e1.getName().compareTo(e1.getName());
        }else { 
            return e1.getAge().compareTo(e2.getAge()); 
        } 
    })
    .forEach(System.out::println);
终止操作

allMatch-检查是否匹配所有元素

boolean  flag = list.stream()
                .allMatch(e->e.getAge()>=30);

anyMatch-检查是否至少匹配一个元素

 boolean b3 = emps.stream()        
     .noneMatch((e) -> e.getStatus().equals(Status.OTHER));    

 

findFirst-返回第一个元素

Optional<Employee> op1 = emps.stream()        
    .sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))        				.findFirst();  

findAny-返回当前流中的任意元素

count-返回流中元素的总个数

max-返回流中最大值

min-返回流中最小值

收集

List-把流中所有元素收集到List中

List<String> list = emps.stream()    
.map(Employee::getName)    
.collect(Collectors.toList());
 list.forEach(System.out::println);

// Set-把流中所有元素收集到Set中,删除重复项

Set<String> set = emps.stream()    
					.map(Employee::getName)    
					.collect(Collectors.toSet()); 
set.forEach(System.out::println);

Map-把流中所有元素收集到Map中,当出现相同的key时会抛异常

Map<String, Integer> map = emps.stream()   
								.collect(Collectors.toMap(Employee::getName, Employee::getAge)); 
System.out.println(map);

flatMap() 流中的每一个数据当做参数,进行操作 ,得到的结果必须 是 一个流,最终会结合成一个流返回

public class StreamDemo03 {
    static List<Employee> list = Arrays.asList(
            new Employee(1001,"胡歌",35),
            new Employee(1002,"彭于晏",30),
            new Employee(1003,"金城武",32),
            new Employee(1004,"宋承宪",31),
            new Employee(1004,"谢霆锋",38)
    );
    public static void main(String[] args) {
        testMap();
        Stream<String> s = Stream.of("aaa","bbb","ccc");
        //map
      /*  Stream<Stream<Character>>  ss = s.map(StreamDemo03::testCharacter);  // {{a,a,a},{b,b,b},{c,c,c}}
        ss.forEach(sss->sss.forEach(System.out::println));*/

        //flatMap
        Stream<Character> haha= s.flatMap(StreamDemo03::testCharacter);  //{a,a,a,b,b,b,c,c,c}
        haha.forEach(System.out::println);
    }

    //map 得到所有的员工信息打印
    public static void testMap(){
        list.stream()
                .map(e->e.getName())
                .forEach(System.out::println);
    }

    //
    public static Stream<Character> testCharacter(String str){
        List<Character> ls = new ArrayList<>();
        for(Character ch:str.toCharArray()){
            ls.add(ch);
        }
        return ls.stream();
    }
}

注意:
1、Stream自己不会存储元素·
2、Stream不会改变源对象。相反,会返回一个持有结果的新Stream。
3、Stream操作是延迟执行的,这意味着他们会等到需要结果的时候才执行。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值