programing

Java 람다에는 두 개 이상의 매개 변수가 있을 수 있는가?

prostudy 2022. 5. 13. 23:48
반응형

Java 람다에는 두 개 이상의 매개 변수가 있을 수 있는가?

자바에서는 람다가 여러 가지 다른 유형을 받아들이도록 하는 것이 가능한가?

즉, 단일 변수 작동:

    Function <Integer, Integer> adder = i -> i + 1;
    System.out.println (adder.apply (10));

바라그는 또한 다음과 같이 작용한다.

    Function <Integer [], Integer> multiAdder = ints -> {
        int sum = 0;
        for (Integer i : ints) {
            sum += i;
        }
        return sum;
    };

    //.... 
    System.out.println ((multiAdder.apply (new Integer [] { 1, 2, 3, 4 })));

하지만 나는 많은 다른 종류의 주장을 받아들일 수 있는 것을 원한다. 예를 들어,

    Function <String, Integer, Double, Person, String> myLambda = a , b, c, d->  {
    [DO STUFF]
    return "done stuff"
    };

기능 내부에 소형 인라인 기능을 탑재해 편의성을 높이는 것이 주 용도다.

구글을 둘러보고 자바의 Function Package를 조사했지만 찾을 수 없었다.이것이 가능한가?

여러 가지 유형 매개변수로 기능 인터페이스를 정의하면 가능하다.그런 체형은 없다.(여러 파라미터를 가진 몇 가지 제한된 유형이 있다.)

@FunctionalInterface
interface Function6<One, Two, Three, Four, Five, Six> {
    public Six apply(One one, Two two, Three three, Four four, Five five);
}

public static void main(String[] args) throws Exception {
    Function6<String, Integer, Double, Void, List<Float>, Character> func = (a, b, c, d, e) -> 'z';
}

나는 그것을 불렀다.Function6여기. 이름은 당신이 재량에 따라, Java 라이브러리에 있는 기존 이름과 충돌하지 않도록 하십시오.


또한 유형 매개변수의 가변 개수를 정의할 수 있는 방법이 없다. 만약 그것이 당신이 요청했던 것이라면 말이다.


스칼라와 같은 일부 언어는 1, 2, 3, 4, 5, 6 등의 유형 매개변수를 사용하여 그러한 유형에서 빌드된 개수를 정의한다.

파라미터가 2개 있는 경우BiFunction. 더 필요한 경우 다음과 같이 자신의 기능 인터페이스를 정의할 수 있다.

@FunctionalInterface
public interface FourParameterFunction<T, U, V, W, R> {
    public R apply(T t, U u, V v, W w);
}

두 개 이상의 매개 변수가 있는 경우 다음과 같이 인수 목록 주위에 괄호를 넣으십시오.

FourParameterFunction<String, Integer, Double, Person, String> myLambda = (a, b, c, d) -> {
    // do something
    return "done something";
};

이 경우 기본 라이브러리(java 1.8)의 인터페이스를 사용할 수 있다.

java.util.function.BiConsumer
java.util.function.BiFunction

인터페이스에는 다음과 같은 작은 기본 방법의 예가 있다.

default BiFunction<File, String, String> getFolderFileReader() {
    return (directory, fileName) -> {
        try {
            return FileUtils.readFile(directory, fileName);
        } catch (IOException e) {
            LOG.error("Unable to read file {} in {}.", fileName, directory.getAbsolutePath(), e);
        }
        return "";
    };
}}

람다를 사용하는 방법 : 세 가지 유형의 조작이 있다.
1. 매개변수 수용 --> 소비자
2. 시험 매개변수 반환 부울 --> 술어
3. 매개변수 및 반환값 조작 --> 기능

Java Functional 인터페이스 최대 두 개의 매개 변수:
단일 매개변수 인터페이스
소비자
술어
함수

2개의 파라미터 인터페이스
바이오 컨슈머
비프레디케이트
바이펑션

이상의 경우 다음과 같이 기능 인터페이스를 생성해야 한다(소비자 유형).

@FunctionalInterface
public interface FiveParameterConsumer<T, U, V, W, X> {
    public void accept(T t, U u, V v, W w, X x);
}

또한 jOOL 라이브러리 - https://github.com/jOOQ/jOOL를 사용할 수 있다.

이미 파라미터 개수가 다른 기능 인터페이스를 준비했다.예를 들어, 당신은org.jooq.lambda.function.Function3, 등으로부터Function0까지Function16.

또 다른 대안은, 이것이 당신의 특정한 문제에 적용되는지는 확실하지 않지만, 어떤 문제에도 적용될 수 있는 것은 사용하는 것이다.UnaryOperatorproperty.function .laurela. 서 지정한 유형을 지정한 유형이 반환되므로 모든 변수를 한 클래스에 넣고 매개 변수로 사용하십시오.

public class FunctionsLibraryUse {

    public static void main(String[] args){
        UnaryOperator<People> personsBirthday = (p) ->{
            System.out.println("it's " + p.getName() + " birthday!");
            p.setAge(p.getAge() + 1);
            return p;
        };
        People mel = new People();
        mel.setName("mel");
        mel.setAge(27);
        mel = personsBirthday.apply(mel);
        System.out.println("he is now : " + mel.getAge());

    }
}
class People{
    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

그래서 이 경우에 네가 가진 수업은Person에는 수많은 인스턴스 변수가 있을 수 있으므로 람다 식의 매개 변수를 변경할 필요가 없다.

관심 있는 사람들을 위해, 나는 java.util.function 라이브러리를 사용하는 방법에 대한 노트를 작성했다: http://sysdotoutdotprint.com/index.php/2017/04/28/java-util-function-library/

일부 람다 함수:

import org.junit.Test;
import java.awt.event.ActionListener;
import java.util.function.Function;

public class TestLambda {

@Test
public void testLambda() {

    System.out.println("test some lambda function");

    ////////////////////////////////////////////
    //1-any input | any output:
    //lambda define:
    Runnable lambda1 = () -> System.out.println("no parameter");
    //lambda execute:
    lambda1.run();


    ////////////////////////////////////////////
    //2-one input(as ActionEvent) | any output:
    //lambda define:
    ActionListener lambda2 = (p) -> System.out.println("One parameter as action");
    //lambda execute:
    lambda2.actionPerformed(null);


    ////////////////////////////////////////////
    //3-one input | by output(as Integer):
    //lambda define:
    Function<String, Integer> lambda3 = (p1) -> {
        System.out.println("one parameters: " + p1);
        return 10;
    };
    //lambda execute:
    lambda3.apply("test");


    ////////////////////////////////////////////
    //4-two input | any output
    //lambda define:
    TwoParameterFunctionWithoutReturn<String, Integer> lambda4 = (p1, p2) -> {
        System.out.println("two parameters: " + p1 + ", " + p2);
    };
    //lambda execute:
    lambda4.apply("param1", 10);


    ////////////////////////////////////////////
    //5-two input | by output(as Integer)
    //lambda define:
    TwoParameterFunctionByReturn<Integer, Integer> lambda5 = (p1, p2) -> {
        System.out.println("two parameters: " + p1 + ", " + p2);
        return p1 + p2;
    };
    //lambda execute:
    lambda5.apply(10, 20);


    ////////////////////////////////////////////
    //6-three input(Integer,Integer,String) | by output(as Integer)
    //lambda define:
    ThreeParameterFunctionByReturn<Integer, Integer, Integer> lambda6 = (p1, p2, p3) -> {
        System.out.println("three parameters: " + p1 + ", " + p2 + ", " + p3);
        return p1 + p2 + p3;
    };
    //lambda execute:
    lambda6.apply(10, 20, 30);

}


@FunctionalInterface
public interface TwoParameterFunctionWithoutReturn<T, U> {
    public void apply(T t, U u);
}

@FunctionalInterface
public interface TwoParameterFunctionByReturn<T, U> {
    public T apply(T t, U u);
}

@FunctionalInterface
public interface ThreeParameterFunctionByReturn<M, N, O> {
    public Integer apply(M m, N n, O o);
}
}

참조URL: https://stackoverflow.com/questions/27872387/can-a-java-lambda-have-more-than-1-parameter

반응형