본문 바로가기

카테고리 없음

자바 람다 문제 정리

▶ 두 합을 더하는 람다

interface Calculation{
    int sum(int x, int y);
}
/*********************************************/
//솔루션
interface SumCalculator{
    int sol_sum(int a, int b);
}
public class exc_1 {
    public static void main(String[] args) {
        Calculation sumation = (x, y) -> {
            return x+y;
        };
        System.out.println(sumation.sum(1,2));

        //******************************************
        SumCalculator sumCalculator = (x,y) -> x+y;
        int result = sumCalculator.sol_sum(7,6);
        System.out.println("정답 : " + result);


    }
}

 

 

 

 

 

▶ 리스트에서 가장 길이가 긴 문자를 찾는 람다 예제

import java.util.Arrays;
import java.util.List;

public class ecx_16 {
    public static void main(String[] args) {
        //Write a Java program to implement a lambda expression
        // to find the length of the longest and smallest string in a list.

        List< String > colors = Arrays.asList("Red", "Green", "Blue", "Orange", "Black");

        // Print the elements of the list
        System.out.println("Elements of the list: " + colors);

        // Find the length of the longest string using lambda expression
        int max_length = colors.stream()
                .mapToInt(String::length)
                .max()
                .orElse(0);
        // Print the length of the longest string
        System.out.println("Length of the longest string: " + max_length);

        // Find the length of the smallest string using lambda expression
        int min_length = colors.stream()
                .mapToInt(String::length)
                .min()
                .orElse(0);
        // Print the length of the smallest string
        System.out.println("Length of the smallest string: " + min_length);
    }


}

 

▶ 두 문자를 합하는 람다 식

 

import java.util.function.BiFunction;

public class exc_10 {
    public static void main(String[] args) {
        //Write a Java program to implement
        // a lambda expression to concatenate two strings.

        String string_fst = "str1";
        String string_scd = "str2";


        BiFunction<String, String, String> concat2
                =(s1, s2) -> s1 + s2;

        String rst = concat2.apply(string_fst, string_scd);
        System.out.println(rst);



        /*----------------------------------------------------------*/
        System.out.println("----------------------sol--------------------------");

        // Define the concatenate lambda expression
        BiFunction<String, String, String> concatenate = (str1, str2) -> str1 + str2;

        // Concatenate two strings using the lambda expression
        String string1 = "Good ";
        String string2 = "Morning!";
        System.out.println("Original strings: " + string1 + ", " +string2);
        String result = concatenate.apply(string1, string2);

        // Print the concatenated string
        System.out.println("\nConcatenated string: " + result);

    }


}

 

 

 

 

 

▶ 두 수를 비교해서 가장 큰 값을 구하는 람다식

 

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

public class exc_11 {
    public static void main(String[] args) {
        List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5);

        Integer minmum = Collections.min(lst);
        Integer maximum = Collections.max(lst);

        System.out.println("Min val : " + minmum);
        System.out.println("Max val : " + maximum);

        /*----------------------------------------------------------*/
        System.out.println("----------------------sol--------------------------");
        // Create a list of integers
        List<Integer> nums = Arrays.asList(12, 15, 0, 8, 7, 9, -6);
        System.out.println("Original values of the said array: "+nums);
        // Find the maximum value using lambda expression
        Optional<Integer> max = nums.stream()
                .max((x, y) -> x.compareTo(y));

        // Find the minimum value using lambda expression
        Optional<Integer> min = nums.stream()
                .min((x, y) -> x.compareTo(y));

        // Print the maximum and minimum values
        System.out.println("Maximum value: " + max.orElse(null));
        System.out.println("Minimum value: " + min.orElse(null));

    }
}

 

▶ 두수의 곱

 

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class exc_12 {
    public static void main(String[] args) {
        List<Integer> lst = Arrays.asList(1,2,3,4,5);

        Integer sum = lst.stream().reduce(0, Integer::sum);
        System.out.println(sum);

        Integer mul = lst.stream().reduce(1, (x,y) -> x *y);
        System.out.println(mul);
    }
}

 

▶ 모든 홀수 및 짝수의 제곱합을 계산하는 람다 식을 구해야함

 

import java.util.Arrays;
import java.util.List;

public class exc_15 {
    public static void main(String[] args) {

        // Write a Java program to implement a lambda expression to calculate the sum of squares of all odd and even numbers in a list.
        List<Integer> list = Arrays.asList(1,2,3,4,5);

        int sum_even = list.stream().filter(i -> i %2==0).reduce(0,Integer::sum);

        System.out.println(sum_even);

        int sum_odd = list.stream().filter(i -> i %2 !=0).reduce(0,Integer::sum);
        System.out.println(sum_odd);

        //문제 해석 잘못함 모든 홀수 및 짝수의 제곱합을 계산하는 람다 식을 구해야함
        List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
        int sum_squares_odd = nums.stream()
                .filter(n ->n %2!=0)
                .mapToInt(n -> n*n)
                .sum();

        int sum_squares_even = nums.stream()
                .filter(n -> n %2==0)
                .mapToInt(n -> n*n)
                .sum();

        System.out.println("odd squares " + sum_squares_odd);
        System.out.println("even squares " + sum_squares_even);



    }
}

 

▶ 특정 문자가 들어있는지 확인하는 방법

 

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class exc_17 {
    public static void main(String[] args) {
        //Write a Java program to implement
        // a lambda expression to check
        // if a list of strings contains a specific word.


        List<String> lst = Arrays.asList("Blue", "Red", "Orange","Yellow");

        boolean isExist = lst.stream().anyMatch("Blue"::equals);

        if(isExist){
            System.out.println("Exists");
        }

        System.out.println("-----------------sol--------------------");

        List < String > colors = Arrays.asList("Red", "Green", "Blue", "Orange", "Black");

        String searchColor = "Orange";

        Predicate<String> containsWord = word -> word.equals(searchColor);

        boolean flag = colors.stream().anyMatch(containsWord);
        System.out.println(searchColor + " exists?" + flag);

    }
}

▶ 람다를 이용해서 perfect 루트가 맞는지 확인하는 법

 

import java.util.function.Predicate;

public class exc_18 {
    public static void main(String[] args) {

        //Write a Java program to implement a lambda expression to check
        // if a given number is a perfect square.
        Predicate<Integer> isPerfectSquare = n ->{
            int sqrt = (int) Math.sqrt(n);
            return sqrt * sqrt ==n;
        };


        int N = 36;
        boolean rst = isPerfectSquare.test(N);
        System.out.println(rst);

    }
}

▶ 빈문자열 채크

 

import java.util.function.Predicate;

interface check_empty{
    boolean stringChecker(String str);
}
public class exc_2 {
    public static void main(String[] args) {
        check_empty check_empty = (param) ->{
          if(param.length() > 0){
              return true;
          }else{
              return false;
          }
        };


        System.out.println(check_empty.stringChecker("check"));
        System.out.println(check_empty.stringChecker(""));

        /*****************************************************************/
        Predicate<String> isEmptyString = str -> str.isEmpty();

        // Test cases
        String str1 = ""; // empty string
        String str2 = "Java lambda expression!"; // non-empty string

        // Check if the strings are empty using the lambda expression
        System.out.println("String 1:" + "''");
        System.out.println("String 1 is empty: " + isEmptyString.test(str1));
        System.out.println("\nString 2:" + str2);
        System.out.println("String 2 is empty: " + isEmptyString.test(str2));

    }
}

 

 

▶ 숫자가 짝수인가 홀수 인가? 채크

 

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class exc_4 {
    public static void main(String[] args) {
        //Problem write Java program to implement a lambda
        //expression to filter out even and odd numbers from a list of integers

        List<Integer> int_lst = Arrays.asList(1, 2, 3, 4, 5, 6);


        int_lst.stream().filter(num -> num % 2==0).collect(Collectors.toList())
                .forEach(System.out::println);
        System.out.println("----------------------------");
        int_lst.stream().filter(num -> num % 2 !=0).collect(Collectors.toList())
                .forEach(System.out::println);
    }
}

 

 

 

▶알파벳 순으로 정리하기

 

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class exc_5 {
    public static void main(String[] args) {
        //Problem 5
        //Write a Java program to implement a lambda expression
        // to sort a list of strings in alphabetical order.
        List<String> lst = Arrays.asList("b", "c", "e", "a", "d");


        lst.sort((str1, str2)->str1.compareToIgnoreCase(str2));
        lst.forEach(System.out::println);
    }
}

 

 

 

 

 

▶중복 요소 제거하기

 

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class exc_7 {
    public static void main(String[] args) {
        //Write a Java program to implement a lambda expression
        // to remove duplicates from a list of integers.
        List<Integer> list = Arrays.asList(1,1,2,3,4,4,5,6,7);

        list.stream().distinct().forEach(System.out::println);
        /*********************************************************/
        System.out.println("-solution------------------------------");



        // Create a list of integers with duplicates
        List<Integer> nums = Arrays.asList(1, 2, 3, 3, 4, 3, 2, 5, 6, 1, 7, 7, 8, 10);
        // Print the list
        System.out.println("List elements " + nums);
        // Remove duplicates using lambda expression
        List<Integer> unique_nums = new ArrayList<>();
        nums.stream()
                .distinct()
                .forEach(unique_nums::add);

        // Print the list without duplicates
        System.out.println("\nList elements without duplicates: " + unique_nums);
    }
}

 

팩토리얼

import java.util.Scanner;
import java.util.function.LongUnaryOperator;
import java.util.stream.LongStream;


public class exc_8 {
    public static void main(String[] args) {
        //Write a lambda expression to implement a lambda expression
        // to calculate the factorial of a given number.

        int number;
        Scanner scn = new Scanner(System.in);
        number = scn.nextInt();

        long result_fst = LongStream.rangeClosed(1, number).reduce(1,(long num1, long num2) -> num1*num2);
        System.out.println(result_fst);


        System.out.println("------------------------------sol------------------------------------");

        // Define the factorial lambda expression
        LongUnaryOperator factorial = n -> {
            long result = 1;
            for (long i = 1; i <= n; i++) {
                result *= i;
            }
            return result;
        };

        // Calculate the factorial of a number using the lambda expression
        long n = 7;
        long factorial_result = factorial.applyAsLong(n);

        // Print the factorial result
        System.out.println("Factorial of " + n + " is: " + factorial_result);
        
    }
}