我有一些Java代码根据一些输入过滤列表.它目前使用lambda,例如:
public List<ComplexObject> retrieveObjectsFilteredByTags(List<String> allowedTags) {
List<ComplexObject> complexObjects = retrieveAllComplexObjects();
return complexObjects
.stream()
.filter( compObject -> allowedTags.contains(compObject.getTag()))
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是将过滤器逻辑移动到另一种方法,使其可重复使用,并且易于单元测试.所以我想使用方法引用代替传递给filter方法的lambda.如果过滤器逻辑是相当静态的(即在编译时已知允许的标签列表),则很容易做到,但我无法弄清楚如何使用过滤器中的动态数据执行此操作.
我想要的是一些使用方法引用然后传递第二个动态参数的方法,即
public List<ComplexObject> retrieveObjectsFilteredByTags(List<String> allowedTags) {
List<ComplexObject> complexObjects = retrieveAllComplexObjects();
return complexObjects
.stream()
.filter(this::filterByAllowedTags, allowedTags)
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
那么我可以做我想做的事情,还是我可能错误地接近这种情况?
我有两个变量如下:
List<Basket> bigBasket = new ArrayList<>();
Basket basket = new Basket();
我写了下面的代码在新增项目之间的关系bigBasket和basket:
for (Fruit specialFruit : bigBasket.get(0).getFruitInBasket()) {
for (Fruit fruit : basket.getFruitInBasket()) {
specialFruit.addRelationship(fruit);
}
}
Run Code Online (Sandbox Code Playgroud)
现在这一切都很好,但是IntelliJ检查了代码并提供了使用方法引用来改进它,所以我得到了以下内容:
for (Fruit specialFruit : bigBasket.get(0).getFruitInBasket()) {
basket.getFruitInBasket().forEach(specialFruit::addRelationship);
}
Run Code Online (Sandbox Code Playgroud)
所以上面的线路较少,但它的实际优势是什么?我并不完全了解Java 8功能的好处,这可能就是为什么我真的不明白发生了什么.
在我看来,假设您对Java 8功能没有太多了解,那么"改进"版本的代码在立即理解正在发生的事情与循环标准的意义上并不是非常易读.
有人可以解释"改进"代码与循环标准的好处吗?
编辑:删除了对lambdas的错误引用.代码只是使用方法引用 - 只是我的一个语言错误!
我班上有私人方法.
public class MyClass {
public void method(){
....
List<String> filteredPaths = Arrays.asList(paths).stream().filter(this::validate).collect(Collectors.toList());
....
}
private boolean validate(String path){
...
}
}
Run Code Online (Sandbox Code Playgroud)
我看到主要问题:
Private method 'validate' is never used.
Run Code Online (Sandbox Code Playgroud)
这个问题已知吗?
怎么解决?解决方法?
如果我创建一个功能界面:
@FunctionalInterface
public class Consumer2<T1, T2> {
void accept(T1 t1, T2 t2);
default Consumer1<T2> curry(T1 t1) {
return (t2) -> accept(t1, t2);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我有一个班级:
public class MyClass {
public void printStrings(String a, String b) {
System.out.println(a + ": " + b);
}
}
MyClass myClass = new MyClass();
Run Code Online (Sandbox Code Playgroud)
现在,如果我想使用我的功能界面,我可以:
Consumer2<String, String> printString = myClass::printStrings;
printString.curry("hello").accept("world");
Run Code Online (Sandbox Code Playgroud)
但我做不了类似的事情:
myClass::printStrings.curry("hello").accept("world");
Run Code Online (Sandbox Code Playgroud)
这是有道理的,因为Java无法知道myClass::printStrings可以应用于功能接口Consumer2.为此,我创建了一个实用程序类:
public class F {
public static <T1, T2> Consumer2<T1, T2> c2(Consumer2<T1, T2> fn) {
return fn;
} …Run Code Online (Sandbox Code Playgroud) 试图了解如何引用实例函数。我已经找到了如何定义吸气剂的方法,但是,设置器给我带来了麻烦。我不确定如何为给定的方法签名和给定的基类编写函数。
Foo::setBar下面是什么类型?
public class Foo {
private String bar;
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
{
//Works great!
Function<Foo, String> func1 = Foo::getBar;
//Compile error ?
Function<Foo, String> func2 = Foo::setBar;
//Compile error ?
Function<Foo, Void, String> func3 = Foo::setBar;
}
Run Code Online (Sandbox Code Playgroud) 我有一个PersonFactory如下界面:
@FunctionalInterface
public interface PersonFactory<P extends Person> {
P create(String firstname, String lastname);
// Return a person with no args
default P create() {
// Is there a way I could make this work?
}
}
Run Code Online (Sandbox Code Playgroud)
本Person类:
public class Person {
public String firstname;
public String lastname;
public Person() {}
public Person(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望能够Person像这样实例化我的:
PersonFactory<Person> personFactory = Person::new;
Person p = personFactory.create(); // …Run Code Online (Sandbox Code Playgroud) java java-8 functional-interface method-reference constructor-reference
鉴于..
List<Foo> copy(List<Foo> foos) {
return foos
.stream()
.map(foo -> new Foo(foo))
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
IntelliJ IDEA 2016.1.1报告new Foo(foo)"可以用方法参考替换".
我知道Foo::newno-arg构造函数的语法,但是没有看到我如何foo作为参数传入.我肯定在这里遗漏了一些东西.
我正在尝试创建一个工作队列类(FooQueue),它具有:
当do函数是静态的时,代码编译,但是当函数是非静态的时,代码编译,即使根据这个,实例函数成员的定义是正确的.
应该改变什么来使其编译/运行?
public class App {
public static void main( String[] args ) {
FooQueue q = new FooQueue();
q.add( FooQueue::dos, new FooItem() ); // this compiles
q.add( q::do1, new FooItem() ); // this does not:
// does not consider q::do1 'delegate'
// as taking 2 parameters,
// with q being the first one
FooQueue q2 = new FooQueue2();
q.add( FooQueue2::dos, new FooItem() ); // want this to give compiler error
q.add( FooQueue2::do1, new FooItem() …Run Code Online (Sandbox Code Playgroud) 假设我有一个Gizmo带有构造函数的类,它接受一个String.假设我想将a转换List<String>为a List<Gizmo>.
我可能会写:
List<String> strings = new ArrayList<>();
List<Gizmo> gizmos = strings
.stream()
.map(str -> new Gizmo(str))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
现在,问题是IntelliJ告诉我我可以用方法引用替换lambda.事实是,我很确定方法引用不能参数.
在Java Precisely 3rd Ed.中,有以下代码片段:
BiConsumer<Double[], Comparator<Double>> arraySorter = Arrays::<Double>sort;
Run Code Online (Sandbox Code Playgroud)
但是,我注意到即使我不在<Double>之后::,方法引用仍然有效(由于类型参数,这是有意义的BiConsumer).
不过,我很困惑,是否有何种情况下::<T>会需要在方法的参考,如果是这样,一个例子将是非常有益.