상세 컨텐츠

본문 제목

[Java] java.util.function

Java/Theory

by 찌니씨 2022. 10. 4. 17:01

본문

title_theory

✔ Supplier

* There is no requirement that a new or distinct result be returned each time the supplier is invoked.
  (호출될 때마다 새로운 결과나 뚜렷한 결과를 반환 X)
* Supplier<T> functionNaim = () -> ""; 
* T result = functionNaim.get(T);

 

Supplier <String> myStringSupplier = () -> "hello world!";
System.out.println(
    "\n" +myStringSupplier.get());

Supplier <Double> myRandomDoubleSupplier = () -> Math.random();
printRandomDoubles(myRandomDoubleSupplier, 5);

//		public static void printRandomDoubles(Supplier <Double> randomSupplier,
//		int count) {
//			for (int i = 0; i < count; i++) {
//				System.out.println(randomSupplier.get());
//			}
//		}

✔ Consumer 받기, 먹보

* Represents an operation that accepts a single input argument and returns no result.
  (단일 입력 인수를 수락하고 결과를 반환 X)
* Consumer<T> functionNaim = () -> "";
* T result = functionNaim.accept(T);

 

Consumer <String> myStringConsumer = (String str) ->
    System.out.println(
        "\n" +str);
myStringConsumer.accept("hello");

List <Integer> integerInputs = Arrays.asList(4, 2, 3);
Consumer <Integer> myIntegerProcessor = x ->
    System.out.println(
        "\n" +"Processing integer " + x);
process(integerInputs, myIntegerProcessor);

//		public static <T> void process(List <T> inputs, Consumer <T> processor) {
//			for (T input : inputs) {
//				processor.accept(input);
//			}
//		}

✔ BiConsumer

 * Represents an operation that accepts two input arguments and returns no result.
  (두 개의 입력 인수를 수락하고 결과를 반환하지 않는 작업)
 * BiConsumer<T, U> functionNaim = () -> "";
 * T result = functionNaim.accept(T);

 

BiConsumer <Integer, Double> myDoubleProcessor =
    (index, input) ->
        System.out.println(
            "\n" +"Processing " + input + " at index " + index);
List <Double> inputs = Arrays.asList(1.1, 2.2, 3.3);
process(inputs, myDoubleProcessor);

//		public static <T> void process(List <T> inputs, BiConsumer <Integer, T> processor) {
//		for (int i = 0; i < inputs.size(); i++) {
//			processor.accept(i, inputs.get(i));
//			}
//		}

 Predicate

 * Represents a predicate (boolean-valued function) of one argument.
  (한 인수의 술어(부울 값 함수)를 나타냄.)
 *
 * Predicate<T> functionNaim = () -> "";
 * T result = functionNaim.test(T);

 

 util.Comparator 비교

 * Represents an operation upon two operands of the same type, producing a result of the same type as the operands.
  (동일한 유형의 두 피연산자에 대한 작업을 나타내며 피연산자와 동일한 유형의 결과를 생성)
 * ex) min, max
 * BinaryOperator functionNaim = () -> "";
 * T result = functionNaim.compare(a, b) <= 0 ? a : b;
 * int compare(T 01, T o2);
 * //String ->CompareTo

 

 util.Collections(Sorts) 정렬

 * Sorts the specified list into ascending order, according to the natural ordering of its elements.
  (요소의 고유 순서에 따라 지정된 목록을 오름차순으로 정렬)
 * Collections.sort(List list) {
 *         list.sort(null);
 *     }

 

public static void main(String[] args) {

    Predicate <Integer> isPositive = x -> x > 0;
    System.out.println(isPositive.test(- 10));

    List <Integer> predicateInputs = Arrays.asList(10, - 5, 4, - 2, 0, 3);
    System.out.println(
        "\n" +"Positive number: " + filter(predicateInputs, isPositive));
    System.out.println(
        "\n" +"Non-positive number: " + filter(predicateInputs, isPositive.negate()));
    System.out.println(
        "\n" +"Non-negative number: "
                       + filter(predicateInputs, isPositive.or(x -> x == 0)));
    System.out.println(
        "\n" +"Positive even numbers: "
                       + filter(predicateInputs, isPositive.and(x -> x % 2 == 0)));

    //		public static <T> List <T> filter(List <T> inputs, Predicate <T> condition) {
    //			List <T> output = new ArrayList <>();
    //			for (T input : inputs) {
    //				if (condition.test(input)) {
    //					output.add(input);
    //				}
    //			}
    //			return output;
    //		}
        List <com.jini.domain.fc_stream.chapter4.model.User> users = new ArrayList <>();
        users.add(new com.jini.domain.fc_stream.chapter4.model.User(3, "Alice"));
        users.add(new com.jini.domain.fc_stream.chapter4.model.User(1, "Chalie"));
        users.add(new User(5, "Bob"));
        System.out.println(users);

        /**

         */

        // u1 <= u2 음수
        // u1 = u2 0
        // u1 >= u2 양수
        Comparator <User> idComparator = (u1, u2) -> u1.getId() - u2.getId();
        Collections.sort(users, idComparator);
        System.out.println(users);

        //a~z
        //a > z 음수
        //a = 1 0
        //a < z 양수
        Collections.sort(users, (u1, u2) ->u1.getName().compareTo(u2.getName()));
        System.out.println(users);

    }
}
public static void printRandomDoubles(Supplier <Double> randomSupplier,
    int count) {
    for (int i = 0; i < count; i++) {
        System.out.println(randomSupplier.get());
    }
}

public static <T> void process(List <T> inputs, Consumer <T> processor) {
    for (T input : inputs) {
        processor.accept(input);
    }
}

public static <T> void process(List <T> inputs, BiConsumer <Integer, T> processor) {
    for (int i = 0; i < inputs.size(); i++) {
        processor.accept(i, inputs.get(i));
    }
}

public static <T> List <T> filter(List <T> inputs, Predicate <T> condition) {
    List <T> output = new ArrayList <>();
    for (T input : inputs) {
        if (condition.test(input)) {
            output.add(input);
        }
    }
    return output;
}

 UnaryOperator

 * Represents an operation on a single operand that produces a result of the same type as its operand.
  (피연산자와 동일한 유형의 결과를 생성하는 단일 피연산자에 대한 작업)
 * static <T> UnaryOperator<T> identity()
 * return<T>

 BinaryOperator

 * Represents an operation upon two operands of the same type, producing a result of the same type as the operands.
  (동일한 유형의 두 피연산자에 대한 작업을 나타내며 피연산자와 동일한 유형의 결과를 생성)
 * ex) min, max
 * BinaryOperator<T> functionNaim = () -> "";
 * T result = functionNaim.compare(a, b) <= 0 ? a : b;

 

 

❗ 해당 내용은 Fastcampus의

25개 백엔드 개발 필수 현업 예제를 통해 마스터하는 JAVA STREAM 강의를 들은 후 정리한 내용입니다.

관련글 더보기

댓글 영역