New Java 8 features

A lambda expression is an anonymous function, that is, a function without a function name. From dynamic reference to dynamic definition, the writing method can be simplified.

Compare two ways of writing:

The syntax of lambda expression is as follows:

(parameters) -> expression
或
(parameters) ->{ statements; }

It also has the following features:

Example:

Java 8 provides us with some interfaces to use:

There are many more, all in Java util. Function package.

Example:

//java7写法
new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println(new Date());
    }
}).start();

//java8 写法
new Thread(()-> System.out.println(new Date())).start();

2、 Stream

A stream is a queue of elements from a data source and supports aggregation operations

There are several ways to create a stream:

   String[] array={"a","b","c","d"};
   Stream<String> stream1 = Stream.of(array);
   Stream<String> stream2 = Arrays.stream(array);
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.stream();
 Stream<String> stream3 = Stream.generate(() -> "love").limit(10);
Stream<BigInteger> bigIntStream = Stream.iterate(BigInteger.ZERO,n -> n.add(BigInteger.ONE)).limit(10);
Stream stream = Stream.concat(stream1,stream2);
Stream<String> wordStream = Pattern.compile("\\W").splitAsStream(sentence);

Stream operation:

Intermediate operation:

Terminate operation:

Code example:

 public static void main(String[] args) {
        List<Integer> list=new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);

        list.stream().filter(x->x>2).forEach(System.out::println);

        list.stream().mapToDouble(x->Double.valueOf(x)).forEach((b)-> System.out.println(b));

        list.stream().flatMap(x->Arrays.stream(new Integer[]{x})).forEach(System.out::println);

        boolean flag = list.stream().anyMatch(x -> x % 3 == 0);

        long count = list.stream().count();
        System.out.println("元素个数:"+count);

        long sum = list.stream().collect(Collectors.summarizingInt(x -> x)).getSum();
        System.out.println("总元素的和是:"+sum);

        Integer integer = list.stream().reduce((a,b) -> a + b).get();
        System.out.println("规约求和:"+integer);

    }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>