Java8中的BiConsumer或Consumer

时间:2018-03-17 03:51:41

标签: java-8

我正在尝试理解/学习Java8中的Consumer / BiConsumer。 test1和test2方法工作正常。

但是如果我试图通过在test3方法中的类中实现BiConsumer来使用旧时尚方式。 然后在类中重写accept方法,str.substring方法无法解析方法substring。

我不能在@FunctionalInterface中使用旧时尚方式,还是在代码中做错了?

public class BiConsumerTest {
  static void test1(String name, Integer count) {
    method1(name, count, (str, i) -> {
      System.out.println(str.substring(i));
    });
  }

  static void test2(String name, Integer count) {
    BiConsumer<String, Integer> consumer = (str, i) -> {
      System.out.println(str.substring(i));
    };

    method1(name, count, consumer);
  }

  private static void method1(String name, Integer count, BiConsumer<String, Integer> consumer) {
    consumer.accept(name, count);
  }

  private void test3(String name, Integer count) {
    BiConsumer<String, Integer>  consumer = new ConsumerImpl<String, Integer>();
    consumer.accept(name, count);
  }

  class ConsumerImpl<String, Integer> implements BiConsumer<String, Integer> {
    @Override
    public void accept(String str, Integer count) {
      str.substring(count);     // str cannot find substring method !!!
    }
  }

  public static void main(String[] args) {
    String name = "aaa bbb ccc";
    Integer count = 6;

    test1(name, count);
    test2(name, count);
  }
}

1 个答案:

答案 0 :(得分:1)

您无法将已知类型的类定义为类型参数(因此这不正确 - ConsumerImpl<String, Integer>)。此外,几乎没有其他语法错误。下面的作品 -

import java.util.function.BiConsumer;

public class TestClass {

    static void test1(String name, Integer count) {
        method1(name, count, (str, i) -> {
            System.out.println(str.substring(i));
        });
    }

    static void test2(String name, Integer count) {
        BiConsumer<String, Integer> consumer = (str, i) -> {
            System.out.println(str.substring(i));
        };

        method1(name, count, consumer);
    }

    private static void method1(String name, Integer count, BiConsumer<String, Integer> consumer) {
        consumer.accept(name, count);
    }

    static void test3(String name, Integer count) {
        BiConsumer<String, Integer> consumer = new ConsumerImpl();
        consumer.accept(name, count);
    }

    static class ConsumerImpl implements BiConsumer<String, Integer> {
        @Override
        public void accept(String str, Integer count) {
            System.out.println(str.substring(count));     // str cannot find substring method !!!
        }
    }

    public static void main(String[] args) {
        String name = "aaa bbb ccc";
        Integer count = 6;

        test1(name, count);
        test2(name, count);
        test3(name, count);
    }
}