Java8随笔

2020-09-17  本文已影响0人  追梦小蜗牛
image.jpg

介绍:

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.

//a simple program to demonstrate the use of stream in java 
import java.util.*; 
import java.util.stream.*; 

class Demo 
{ 
public static void main(String args[]) 
{ 

    // create a list of integers 
    List<Integer> number = Arrays.asList(2,3,4,5); 

    // demonstration of map method 
    List<Integer> square = number.stream().map(x -> x*x). 
                        collect(Collectors.toList()); 
    System.out.println(square); 

    // create a list of String 
    List<String> names = 
                Arrays.asList("Reflection","Collection","Stream"); 

    // demonstration of filter method 
    List<String> result = names.stream().filter(s->s.startsWith("S")). 
                        collect(Collectors.toList()); 
    System.out.println(result); 

    // demonstration of sorted method 
    List<String> show = 
            names.stream().sorted().collect(Collectors.toList()); 
    System.out.println(show); 

    // create a list of integers 
    List<Integer> numbers = Arrays.asList(2,3,4,5,2); 

    // collect method returns a set 
    Set<Integer> squareSet = 
        numbers.stream().map(x->x*x).collect(Collectors.toSet()); 
    System.out.println(squareSet); 

    // demonstration of forEach method 
    number.stream().map(x->x*x).forEach(y->System.out.println(y)); 

    // demonstration of reduce method 
    int even = 
    number.stream().filter(x->x%2==0).reduce(0,(ans,i)-> ans+i); 

    System.out.println(even); 
} 
} 

[4, 9, 16, 25]
[Stream]
[Collection, Reflection, Stream]
[16, 4, 9, 25]
4
9
16
25
6

总结:

淡定、平和的心态,顺势而为......

上一篇 下一篇

猜你喜欢

热点阅读