Java 8 new features: 2-Consumer (Consumer) interface

Source: Internet
Author: User
Tags iterable

Original

In the previous article, the use of such a method:

List.foreach (new consumer<integer>() {            @Override            publicvoid Accept (Integer t) {                System.out.println (t);            }                    });

here 's the point. The foreach method of the List ;

/* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * ORACLE proprietary/confidential. Use are subject to license terms. */package java.lang;import java.util.iterator;import Java.util.objects;import java.util.spliterator;import Java.util.spliterators;import java.util.function.consumer;/** * Implementing this interface allows a object to be the tar Get of * the "For-each loop" statement. See * <strong> * <a href= "{@docRoot}/: /technotes/guides/language/foreach.html ">for-each loop</a> * </strong> * * @param <T> the type of El Ements returned by the iterator * * @since 1.5 * @jls 14.14.2 the enhanced for statement */public interface iterable<t& Gt     {/** * Returns an iterator over elements of type {@code T}.     * * @return an Iterator.    */iterator<t> Iterator (); /** * Performs the given action for each element of the {@code iterable} * until all elements has been processed or the action throws an * exception. Unless otherwise specified by the implementing class, * actions is performed in the Order of iteration (if an Iterati  On order * is specified).     Exceptions thrown by the action is relayed to the * caller. * For each element of iterable, execute the given action until all elements are executed, or throw an exception. If not specified by the implementation class, the actions are executed in the order of the iterations. Whether the exception is thrown depends on the caller. * * @implSpec * <p>the default implementation behaves as if: * <pre>{@code * for (T t:th     IS) * action.accept (t); *}</pre> * * @param action the action to being performed for each element * @throws NullPointerException I        f The specified action is NULL * @since 1.8 */default void ForEach (CONSUMER&LT;? Super T> Action) {        Objects.requirenonnull (action);        for (t t:this) {action.accept (t);     }}/** * Creates a {@link spliterator} over the elements described by this * {@code iterable}. * * @implSpec * The default implementation CREates an * <em><a href= "spliterator.html#binding" >early-binding</a></em> * spliterator fro  M the iterable ' s {@code Iterator}.     The Spliterator * inherits the <em>fail-fast</em> properties of the iterable ' s iterator.  * * @implNote * The default implementation should usually be overridden. The * Spliterator returned by the default implementation have poor splitting * capabilities, is unsized, and does n OT report any spliterator * characteristics.     Implementing classes can nearly always provide a * better implementation.     * * @return a {@code spliterator} over the elements described by this * {@code iterable}. * @since 1.8 */default spliterator<t> Spliterator () {return spliterators.spliteratorunknownsize (ITER    Ator (), 0); }}

  

This method belongs to the Iterable interface, and is a new method of 1.8 , it has a default implementation method, with the keyword default decoration, that is, in the In JDK1.8 , the interface is no longer required to be an abstract method, but it can have an implementation body, and the method with the implementation needs to be modified with the default keyword.

look again . Consumer interface.

/** * Represents an operation, accepts a single input argument and returns no * result. Unlike most other functional interfaces, {@code Consumer} are expected * to operate via side-effects. * * Represents an operation, receives a parameter, and does not return a result, unlike most other functional interfaces, the consumer interface expects to operate with a negative effect. (that is, it might manipulate the incoming parameter data, and here is what it says about the negative effect.) ) * * <p>this is a <a href= "package-summary.html" >functional interface</a> * whose functional method is {@link #accept (Object)}.  * This is a functional interface by the Accept * @param <T> the type of the input to the operation * * @since 1.8 */@FunctionalInterfacepublic Interface consumer<t>

  

For the previous example, List.foreach (i-System.out.println (i)); What is the parameter of this I? Since there is only one parameter, the compiler can automatically infer the type i belong to, similarly, you can also display the type that specifies it, just like this List.foreach ((Integer i) System.out.println (i));, here is the need to add parentheses.

In other languages, lambda expression types are functions, but in Java ,lambda expressions are objects, and they must be attached to a functional interface ( Functional Interface).

So for the implementation of the functional interface, you can write this:

For example, there are functional interfaces as follows:
Package Com.demo.jdk8;public interface Animal {void eat (String food);}

  

in the previous Lambda , there was a word for the functional interface

1,This can be written in the place where the call is made (LAMDBA expressions):
Animal A = food-and {System.out.println (food);}; A.eat ("fish");

so write and write a class implementation Animal interface, and then new comes out the same. But this code will be more concise.

2.you can write this in a method reference .(Method References):
Animal a = System.out::p rintln;a.eat ("meat");

  

Java 8 new features: 2-Consumer (Consumer) interface

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.