Java Consumer Functional Interface

Java Consumer tutorial shows how to work with the Consumer functional interface in Java.

如何使用Java中的Consumer函数式接口

Consumer

Java Consumer is a functional interface which represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects.

Java Consumer是一个函数式接口,代表一个接受单个输入参数且不返回结果的操作。与大多数其它函数式接口不同,Consumer有望通过副作用进行操作

@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
}

The Consumer's functional method is accept(Object). It can be used as the assignment target for a lambda expression or method reference.

消费者的功能方法是accept(Object)。它可用作lambda表达式或方法引用的分配目标

Java Consumer example

The following example creates a simple consumer.

以下示例创建一个简单的consumer

package com.zetcode.consumer;

import java.util.function.Consumer;

public class ConsumerEx {

    public static void main(String[] args) {

        Consumer<String> showThreeTimes = value -> {

            System.out.println(value);
            System.out.println(value);
            System.out.println(value);
        };

        showThreeTimes.accept("blue sky");
        showThreeTimes.accept("old falcon");
     }
}

The showThreeTimes consumer prints the input three times.

showThreeTimes consumer将输入打印三遍

blue sky
blue sky
blue sky
old falcon
old falcon
old falcon

This is the output

Java IntConsumer

IntConsumer represents an operation that accepts a single int-valued argument and returns no result. This is the primitive type specialization of Consumer for int.

IntConsumer表示一个接受单个int值参数且不返回结果的操作。这是专门用于Int的Consumer的原始类型。

package com.zetcode.consumer;

import java.util.function.Consumer;
import java.util.function.IntConsumer;

public class ConsumerEx2 {

    public static void main(String[] args) {

        Consumer<Integer> printMultiplyBy100 = (val) -> System.out.println(val * 100);

        printMultiplyBy100.accept(3);;
        printMultiplyBy100.accept(4);;
        printMultiplyBy100.accept(5);

        IntConsumer printMultiplyBy500 = a -> System.out.println(a * 50);
        printMultiplyBy500.accept(1);
        printMultiplyBy500.accept(2);
        printMultiplyBy500.accept(3);
    }
}

In the example, the consumers multiply the input value.

在示例中,consumers将输入值相乘

300
400
500
50
100
150

This is the output.

Java Consumer forEach

The forEach method accepts a Consumer as a parameter. The consumer can be simplified with a lambda expression or a method reference.

forEach方法接受Consumer作为参数。可以使用lambda表达式或方法引用来简化consumer

// java 11+
package com.zetcode.consumer;

import java.util.List;
import java.util.function.Consumer;

public class ConsumerEx3 {

    public static void main(String[] args) {

        List<String> words = List.of("falcon", "wood", "rock", "forest",
                "river", "water");

        words.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {

                System.out.println(s);
            }
        });
    }
}

Output

falcon
wood
rock
forest
river
water

Java Consumer andThen

The andThen method returns a composed Consumer that performs, in sequence, this operation followed by the next operation.

package com.zetcode.consumer;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerEx4 {

    public static void main(String[] args) {

        ArrayList<Integer> vals = new ArrayList<Integer>();
        vals.add(2);
        vals.add(4);
        vals.add(6);
        vals.add(8);

        Consumer<List<Integer>> addTwo = list -> {
            for (int i = 0; i < list.size(); i++) {
                list.set(i, 2 + list.get(i));
            }
        };

        Consumer<List<Integer>> showList = list ->
                list.forEach(System.out::println);

        addTwo.andThen(showList).accept(vals);
    }
}

In the example, we add value 2 to each of the elements in the list and then we print all the elements.

在示例中,我们将值2添加到列表中的每个元素,然后打印所有元素

Output
4
6
8
10

This is the output.

In the following example, we work with a list of products.

在以下示例中,使用产品列表

package com.zetcode.consumer;

import java.math.BigDecimal;

public class Product {

    private String name;
    private BigDecimal price;

    public Product(String name, BigDecimal price) {
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public BigDecimal getPrice() {
        return price;
    }

    public void setPrice(BigDecimal price) {
        this.price = price;
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder("Product{");
        sb.append("name='").append(name).append('\'');
        sb.append(", price=").append(price);
        sb.append('}');
        return sb.toString();
    }
}

This is the Product class.

package com.zetcode.consumer;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerEx5 {

    private static RoundingMode ROUNDING_MODE = RoundingMode.HALF_EVEN;
    private static int DECIMALS = 2;

    public static void main(String[] args) {

        List<Product> products = new ArrayList<>();
        products.add(new Product("A", new BigDecimal("2.54")));
        products.add(new Product("B", new BigDecimal("3.89")));
        products.add(new Product("C", new BigDecimal("5.99")));
        products.add(new Product("D", new BigDecimal("9.99")));

        Consumer<Product> incPrice = p -> {
            p.setPrice(rounded(p.getPrice().multiply(new BigDecimal("1.1"))));
        };

        process(products, incPrice.andThen(System.out::println));
    }

    private static BigDecimal rounded(BigDecimal number) {
        return number.setScale(DECIMALS, ROUNDING_MODE);
    }

    private static void process(List<Product> data, Consumer<Product> cons) {
        for (Product e : data) {
            cons.accept(e);
        }
    }
}

This example increases the prices of products by 10%.

本示例将产品价格提高了10%

Consumer<Product> incPrice = p -> {
    p.setPrice(rounded(p.getPrice().multiply(new BigDecimal("1.1"))));
};

The consumer increases the product price by 10% and rounds the value.

consumer将产品价格提高10%并四舍五入

process(products, incPrice.andThen(System.out::println));

We increase the prices and then print the modified products.

我们提高价格,然后打印修改的产品

private static void process(List<Product> data, Consumer<Product> cons) {

    for (Product e : data) {

        cons.accept(e);
    }
}

The consumer is applied on each product of the list.

consumer应用于列表的每个产品

Output
Product{name='A', price=2.79}
Product{name='B', price=4.28}
Product{name='C', price=6.59}
Product{name='D', price=10.99}

This is the output.

Java Consumer custom forEach

The following example creates a custom, generic forEach method.

下面的示例创建一个自定义的通用forEach方法

package com.zetcode.consumer;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerEx6 {

    public static void main(String[] args) {

        List<Integer> data = List.of(1, 2, 3, 4, 5, 6, 7);

        // Consumer<Integer> consumer = (Integer x) -> System.out.println(x);
        Consumer<Integer> consumer = System.out::println;
        forEach(data, consumer);

        System.out.println("--------------------------");

        forEach(data, System.out::println);
    }

    static <T> void forEach(List<T> data, Consumer<T> consumer) {
        for (T t : data) {
            consumer.accept(t);
        }
    }
}
Output
1
2
3
4
5
6
7
--------------------------
1
2
3
4
5
6
7

This is the output.

In this tutorial, we have worked with Java Consumer interface.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值