我有一堆带有此签名的方法:
public void sideEffects() {...}
public void foo() {...}
public void bar() {...}
Run Code Online (Sandbox Code Playgroud)
(也就是说,它们返回void并且没有参数)并且我希望能够通过执行以下操作来填充List:
list.add(MyClass::sideEffects);
list.add(MyClass::foo);
list.add(MyClass::bar);
Run Code Online (Sandbox Code Playgroud)
但是,我无法在支持此签名@FunctionalInterface的java.util.function包中找到内置的.我是否必须为此创建自己@FunctionalInterface的?
interface New<T> {
boolean func(T n, T v);
}
Run Code Online (Sandbox Code Playgroud)
class MyFunc<T>{
T val;
MyFunc(T val){
this.val = val;
}
void Set(T val){
this.val = val;
}
T Get(){
return val;
}
boolean isEqual(MyFunc<T> o){
if(val == o.val) return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
public class Main {
static <T> boolean check(New<T> n , T a, T b){
return n.func(a,b);
}
public static void main(String args[]){
int a = 321;
MyFunc<Integer> f1 = new MyFunc<Integer>(a);
MyFunc<Integer> f2 = new MyFunc<Integer>(a);
boolean result; …Run Code Online (Sandbox Code Playgroud) java.util.function.Predicate有一些有用的方法等and,or等,其比创建具有多个逻辑运算符的托架狂欢更简洁.不幸的是,似乎没有办法使用这些函数而没有实际上首先明确地使用谓词...
Predicate<String> predicate = String::isEmpty;
Predicate<String> predicateWithAnd = predicate.and( MyClass::testSomething );
Run Code Online (Sandbox Code Playgroud)
有没有办法只在一个语句中创建第二谓词(因此"保存"变量),如...
Predicate<String> predicateWithAnd = (String::isEmpty).and( MyClass::testSomething ); // That doesn't seem to work ;-)
Run Code Online (Sandbox Code Playgroud)
只是好奇...
java functional-programming predicate java-8 method-reference
我最近把手放在Java 8上并尝试使用方法参考.我正在尝试不同类型的方法引用,并陷入"引用特定类型的任意对象的实例方法"类型中.
String[] arr = {"First", "Second", "Third", "Fourth"};
Arrays.sort(arr, String::compareToIgnoreCase);
Run Code Online (Sandbox Code Playgroud)
这非常有效.但是当我尝试通过其类型引用用户定义类的方法时:
Demo2[] arr = {a, b};
Arrays.sort(arr, Demo2::compare);
Run Code Online (Sandbox Code Playgroud)
这将编译时错误显示为"无法从静态上下文引用非静态方法".
这是Demo2类:
public class Demo2 implements Comparator<Demo2> {
Integer i;
Demo2(Integer i1){
i = i1;
}
public Integer getI() {
return i;
}
@Override
public int compare(Demo2 o1, Demo2 o2) {
return o1.getI().compareTo(o2.getI());
}
}
Run Code Online (Sandbox Code Playgroud) 我试图转换方法的主体boolean exists(String value, boolean isCaseSensitive):
for(String str : existingNames){
if(isCaseSensitive ? str.equals(name) : str.equalsIgnoreCase(name)){
return true;
}
}
return false;
Run Code Online (Sandbox Code Playgroud)
到使用java8方法引用的解决方案:
Predicate<String> equalityPred = isCaseSensitive ?
name::equals :
name::equalsIgnoreCase;
return existingNames.stream().anyMatch(equalityPred);
Run Code Online (Sandbox Code Playgroud)
然后我看到这种方式在相反的方向上执行相等(例如value.equals(str)).
有没有办法解决这个问题,仍然使用方法引用,如果没有什么是java8方式.
我没有达到要求:
Employee.java
public boolean isAdult(Integer age) {
if(age >= 18) {
return true;
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
谓词.java
private Integer age;
Predicate<Integer> isAdult;
public PredicateAnotherClass(Integer age, Predicate<Integer> isAdult) {
this.age = age;
System.out.println("Test result is "+ isAdult(age));
}
public void testPredicate() {
System.out.println("Calling the method defined in the manager class");
}
Run Code Online (Sandbox Code Playgroud)
现在,我的目标是使用class中定义的方法测试要传递给的年龄是否Predicate成年Employee,为此我要传递在Predicate类的构造函数中传递的方法引用。
但是我不知道如何调用在Employee类中定义的方法,下面是我的测试类:-
public class PredicateTest {
public static void main(String[] args) {
PredicateManager predicateManager = new PredicateManager();
PredicateAnotherClass predicateAnotherClass …Run Code Online (Sandbox Code Playgroud) 我有一个案例如下:
RowDataSet rdsHavingMaxNumericValue = dataList.stream()
.filter(r -> r.getLong(NUMERIC_VALUE) != null)
.max((r1, r2) -> r1.getId().compareTo(r2.getId()))
.get();
Run Code Online (Sandbox Code Playgroud)
我有两种情况需要根据情况找到最小值或最大值?如何用函数替换第三行的调用max,以便它直接使用.apply()方法并执行操作?
我成功分配了Collection.max或Collection min,如下所示:
BiFunction<List<RowDataSet>, Comparator<RowDataSet>, RowDataSet> mrOrlrOperation = expComponents[0] == 'M' ? Collections::max : Collections::min;
Run Code Online (Sandbox Code Playgroud)
我用它如下:
RowDataSet rds = mrOrlrOperation.apply(dataList, <some comparator>);
Run Code Online (Sandbox Code Playgroud) 我正在学习Java 8,我遇到了一个告诉我这样做的任务.我使用lambda工作但是赋值仍然坚持使用方法引用.
我的lambda代码是
package java8training.unit2;
import java.util.List;
import java8training.artifacts.CentralDataBase;
public class Solution2 {
public static void main(String[] args) {
List<String> words = CentralDataBase.words;
words.stream().map(s -> " " + s).forEach(System.out::println);
}
}
Run Code Online (Sandbox Code Playgroud)
目前我认为不可能更换lambda
s -> " " + s
Run Code Online (Sandbox Code Playgroud)
用它的方法参考,还是我错了?
背景:
我想computeIfAbsent在a上使用该功能Map.但是,当我使用时,我收到编译错误
String.我使用时没有编译错误
Integer.String.插图:
以下陈述是合法的:
Map<Integer, List<Long>> map = new HashMap<>();
Integer key = Integer.valueOf(0);
Long value = Long.valueOf(2);
map.computeIfAbsent(key, ArrayList::new).add(value); // No compilation error
Run Code Online (Sandbox Code Playgroud)
以下陈述是非法的:
Map<String, List<Long>> map = new HashMap<>();
String key = "myKey";
Long value = Long.valueOf(2);
map.computeIfAbsent(key, ArrayList::new).add(value); // Compilation error: The type ArrayList does not define ArrayList(String) that is applicable here
Run Code Online (Sandbox Code Playgroud)
以下陈述是合法的 …
为什么将一个参数的方法引用作为期望类型的参数(BiConsumer抽象方法需要两个参数)传递是合法的?
例:
class Experiment {
private String name;
public Experiment(String name) {
this.name = name;
}
public void oneParamMethod(Object o) {
System.out.println(this.name + " and " + o);
}
public <T, S> void executeBiConsumer(BiConsumer<T, S> biCon, T in1, S in2) {
biCon.accept(in1, in2);
}
public static void main(String[] args) {
// notice that the name is "INSTANCE", but it won't be printed out
Experiment exp = new Experiment("INSTANCE");
// executeBiConsumer expects a functional of two params but is …Run Code Online (Sandbox Code Playgroud) method-reference ×10
java ×9
java-8 ×8
lambda ×3
java-stream ×2
predicate ×2
hashmap ×1
this ×1