Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

Java Gold 関数型インターフェイス・ラムダ式 例題100本ノック

Last updated at Posted at 2024-08-29

次のコードの出力を答えてください。
※問題番号に★がついているものは時間があまりない人は無視してください。

問1

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<String, Integer> lengthFunction = str -> str.length();
        System.out.println(lengthFunction.apply("Java Programming"));
    }
}
解答
16

問2

import java.util.function.BiConsumer;

public class Example {
    public static void main(String[] args) {
        BiConsumer<Integer, Integer> addConsumer = (a, b) -> System.out.println(a + b);
        addConsumer.accept(5, 3);
    }
}
解答
8

問3

import java.util.function.Predicate;

public class Example {
    public static void main(String[] args) {
        Predicate<String> nonEmptyPredicate = str -> !str.isEmpty();
        System.out.println(nonEmptyPredicate.test("Hello"));
        System.out.println(nonEmptyPredicate.test(""));
    }
}
解答
true
false

問4

import java.util.function.BinaryOperator;

public class Example {
    public static void main(String[] args) {
        BinaryOperator<Integer> minOperator = (a, b) -> a < b ? a : b;
        System.out.println(minOperator.apply(7, 4));
    }
}
解答
4

問5

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<Integer, Integer> squareFunction = num -> num * num;
        System.out.println(squareFunction.apply(6));
    }
}
解答
36

問6

import java.util.function.Consumer;

public class Example {
    public static void main(String[] args) {
        Consumer<String> printConsumer = str -> System.out.println("Message: " + str);
        printConsumer.accept("Java 8");
    }
}
解答
Message: Java 8

問7

import java.util.function.UnaryOperator;

public class Example {
    public static void main(String[] args) {
        UnaryOperator<Integer> incrementOperator = num -> num + 1;
        System.out.println(incrementOperator.apply(10));
    }
}
解答
11

問8

import java.util.function.BiFunction;

public class Example {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> multiplyFunction = (a, b) -> a * b;
        System.out.println(multiplyFunction.apply(3, 4));
    }
}
解答
12

問9

import java.util.function.Supplier;

public class Example {
    public static void main(String[] args) {
        Supplier<String> helloSupplier = () -> "Hello, World!";
        System.out.println(helloSupplier.get());
    }
}
解答
Hello, World!

問10

import java.util.function.BiPredicate;

public class Example {
    public static void main(String[] args) {
        BiPredicate<String, Integer> lengthGreaterThan = (str, length) -> str.length() > length;
        System.out.println(lengthGreaterThan.test("Java", 3));
        System.out.println(lengthGreaterThan.test("Java", 5));
    }
}
解答
true
false

問11

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<Integer, String> intToString = num -> "Number: " + num;
        System.out.println(intToString.apply(42));
    }
}
解答
Number: 42

問12

import java.util.function.Consumer;

public class Example {
    public static void main(String[] args) {
        Consumer<String> upperCaseConsumer = str -> System.out.println(str.toUpperCase());
        upperCaseConsumer.accept("java");
    }
}
解答
JAVA

問13

import java.util.function.Supplier;

public class Example {
    public static void main(String[] args) {
        Supplier<Integer> randomSupplier = () -> (int) (Math.random() * 100);
        System.out.println(randomSupplier.get());
    }
}
解答 0 から 99 の間のランダムな整数を出力します。

問14

import java.util.function.BinaryOperator;

public class Example {
    public static void main(String[] args) {
        IntPredicate isPrime = num -> {return num > 1 &&
	        		IntStream.iterate(2, i -> i <= Math.sqrt(num), i -> i + 1)
	        				  .noneMatch(i -> num % i == 0);
        };
	        
	        System.out.println(isPrime.test(OptionalInt.of(5).getAsInt()));
    }
}
解答
true

1より大きく、その整数自体でしか割り切れない素数か否かを判定しています。

問15

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<String, String> reverseFunction = str -> new StringBuilder(str).reverse().toString();
        System.out.println(reverseFunction.apply("Java"));
    }
}
解答
avaJ

問16

import java.util.function.Predicate;

public class Example {
    public static void main(String[] args) {
        Predicate<Integer> isEven = num -> num % 2 == 0;
        System.out.println(isEven.test(4));
        System.out.println(isEven.test(7));
    }
}
解答
true
false

問17

import java.util.function.BiConsumer;

public class Example {
    public static void main(String[] args) {
        BiConsumer<String, Integer> printMessage = (message, times) -> {
            for (int i = 0; i < times; i++) {
                System.out.println(message);
            }
        };
        printMessage.accept("Repeat", 3);
    }
}
解答
Repeat
Repeat
Repeat

問18

import java.util.function.UnaryOperator;

public class Example {
    public static void main(String[] args) {
        UnaryOperator<String> exclaimOperator = str -> str + "!";
        System.out.println(exclaimOperator.apply("Hello"));
    }
}
解答
Hello!

問19

import java.util.function.BiPredicate;

public class Example {
    public static void main(String[] args) {
        BiPredicate<Integer, Integer> isGreaterThan = (a, b) -> a > b;
        System.out.println(isGreaterThan.test(5, 3));
        System.out.println(isGreaterThan.test(2, 4));
    }
}
解答
true
false

問20

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<String, String> toUpperCaseFunction = String::toUpperCase;
        System.out.println(toUpperCaseFunction.apply("java"));
    }
}
解答
JAVA

問21

import java.util.function.UnaryOperator;

public class Example {
    public static void main(String[] args) {
        UnaryOperator<Integer> doubleOperator = num -> num * 2;
        System.out.println(doubleOperator.apply(7));
    }
}
解答
14

問22

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<String, Integer> countVowels = str -> (int) str.chars()
                                                               .filter(c -> "AEIOUaeiou".indexOf(c) != -1)
                                                               .count();
        System.out.println(countVowels.apply("Programming"));
    }
}
解答
3
文字列 "Programming" の母音の数は 3 です。

問23

import java.util.function.BiFunction;

public class Example {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> maxFunction = (a, b) -> a > b ? a : b;
        System.out.println(maxFunction.apply(10, 20));
    }
}
解答
20

問24

import java.util.function.Consumer;

public class Example {
    public static void main(String[] args) {
        Consumer<String> reverseConsumer = str -> {
            String reversed = new StringBuilder(str).reverse().toString();
            System.out.println(reversed);
        };
        reverseConsumer.accept("Java");
    }
}
解答
avaJ

問25

import java.util.function.Predicate;

public class Example {
    public static void main(String[] args) {
        Predicate<String> isLongerThanFive = str -> str.length() > 5;
        System.out.println(isLongerThanFive.test("HelloWorld"));
        System.out.println(isLongerThanFive.test("Hi"));
    }
}
解答
true
false

問26

import java.util.function.Supplier;

public class Example {
    public static void main(String[] args) {
        Supplier<Double> randomDoubleSupplier = () -> Math.random();
        System.out.println(randomDoubleSupplier.get());
    }
}
解答 0.0 から 1.0 の間のランダムな小数を出力します。

問27

import java.util.function.UnaryOperator;

public class Example {
    public static void main(String[] args) {
        UnaryOperator<String> addPrefixOperator = str -> "Prefix_" + str;
        System.out.println(addPrefixOperator.apply("Test"));
    }
}
解答
Prefix_Test

問28

import java.util.function.BiPredicate;

public class Example {
    public static void main(String[] args) {
        BiPredicate<String, String> startsWith = (str, prefix) -> str.startsWith(prefix);
        System.out.println(startsWith.test("Java Programming", "Java"));
        System.out.println(startsWith.test("Java Programming", "Programming"));
    }
}
解答
true
false

問29

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<Integer, Integer> factorial = num -> {
            int result = 1;
            for (int i = 1; i <= num; i++) {
                result *= i;
                System.out.println(result);
            }
            return result;
        };
        factorial.apply(5);
    }
}
解答
1
2
6
24
120

問30

import java.util.function.BiConsumer;

public class Example {
    public static void main(String[] args) {
        BiConsumer<String, Integer> repeatString = (str, times) -> {
            for (int i = 0; i < times; i++) {
                System.out.println(str);
            }
        };
        repeatString.accept("Repeat", 2);
    }
}
解答
Repeat
Repeat

問31

import java.util.function.Consumer;

public class Example {
    public static void main(String[] args) {
        Consumer<Integer> printSquare = num -> System.out.println(num * num);
        printSquare.accept(8);
    }
}
解答
64

問32

import java.util.function.BiFunction;

public class Example {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> addFunction = (a, b) -> a + b;
        System.out.println(addFunction.apply(5, 6));
    }
}
解答
11

問33

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<String, String> toLowerCaseFunction = String::toLowerCase;
        System.out.println(toLowerCaseFunction.apply("JAVA"));
    }
}
解答
java

問34

import java.util.function.Predicate;

public class Example {
    public static void main(String[] args) {
        Predicate<Integer> isPositive = num -> num > 0;
        System.out.println(isPositive.test(-5));
        System.out.println(isPositive.test(0));
        System.out.println(isPositive.test(5));
    }
}
解答
false
false
true

問35

import java.util.function.UnaryOperator;

public class Example {
    public static void main(String[] args) {
        UnaryOperator<String> addSuffixOperator = str -> str + "Suffix";
        System.out.println(addSuffixOperator.apply("String"));
    }
}
解答
StringSuffix

問36

import java.util.function.BiConsumer;

public class Example {
    public static void main(String[] args) {
        BiConsumer<Integer, Integer> printDifference = (a, b) -> System.out.println(a - b);
        printDifference.accept(9, 3);
    }
}
解答
6

問37

import java.util.function.Supplier;

public class Example {
    public static void main(String[] args) {
        Supplier<String> currentTimeSupplier = () -> java.time.LocalTime.now().toString();
        System.out.println(currentTimeSupplier.get());
    }
}
解答

現在の時刻を文字列で出力します。

問38

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<Double, String> toStringFunction = Object::toString;
        System.out.println(toStringFunction.apply(3.14));
    }
}
解答
3.14
浮動小数点数 3.14 を文字列に変換して出力します。

問39

import java.util.function.BiPredicate;

public class Example {
    public static void main(String[] args) {
        BiPredicate<String, String> equalsIgnoreCase = (str1, str2) -> str1.equalsIgnoreCase(str2);
        System.out.println(equalsIgnoreCase.test("Java", "java"));
        System.out.println(equalsIgnoreCase.test("Java", "JAVA"));
        System.out.println(equalsIgnoreCase.test("Java", "Python"));
    }
}
解答
true
true
false
文字列 "Java" は "java" と "JAVA" に等しく、"Python" には等しくありません。

問40

import java.util.function.BiFunction;

public class Example {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Double> divideFunction = (a, b) -> (double) a / b;
        System.out.println(divideFunction.apply(9, 3));
    }
}
解答
3.0

問41

import java.util.function.BiFunction;

public class Example {
    public static void main(String[] args) {
        BiFunction<String, Integer, String> repeatString = (str, times) -> str.repeat(times);
        System.out.println(repeatString.apply("Hello", 3));
    }
}
解答
HelloHelloHello
文字列 "Hello" を 3 回繰り返して出力します。

問42

import java.util.function.Consumer;

public class Example {
    public static void main(String[] args) {
        Consumer<String> printUpperCase = str -> System.out.println(str.toUpperCase());
        printUpperCase.accept("java");
    }
}
解答
JAVA

問43

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<String, Integer> lengthFunction = String::length;
        System.out.println(lengthFunction.apply("Function"));
    }
}
解答
8

問44

import java.util.function.Predicate;

public class Example {
    public static void main(String[] args) {
        Predicate<String> isEmpty = String::isEmpty;
        System.out.println(isEmpty.test(""));
        System.out.println(isEmpty.test("Non-empty"));
    }
}
解答
true
false

問45

import java.util.function.Supplier;

public class Example {
    public static void main(String[] args) {
        Supplier<Integer> randomIntSupplier = () -> (int) (Math.random() * 100);
        System.out.println(randomIntSupplier.get());
    }
}
解答 0 から 99 の間のランダムな整数を出力します。

問46

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<Integer, String> toHexFunction = Integer::toHexString;
        System.out.println(toHexFunction.apply(255));
    }
}
解答
ff
整数 255 を 16 進数に変換して出力します。

問47

import java.util.function.UnaryOperator;

public class Example {
    public static void main(String[] args) {
        UnaryOperator<String> trimOperator = String::trim;
        System.out.println(trimOperator.apply("  Trim Me  "));
    }
}
解答
Trim Me
文字列 " Trim Me " の前後の空白を取り除いて出力します。

問48

import java.util.function.BiFunction;

public class Example {
    public static void main(String[] args) {
        BiFunction<String, String, String> concatenateFunction = String::concat;
        System.out.println(concatenateFunction.apply("Hello, ", "World!"));
    }
}
解答
Hello, World!

問49

import java.util.function.BiConsumer;

public class Example {
    public static void main(String[] args) {
        BiConsumer<String, Integer> printRepeated = (str, times) -> {
            for (int i = 0; i < times; i++) {
                System.out.print(str + " ");
            }
        };
        printRepeated.accept("Repeat", 4);
    }
}
解答
Repeat Repeat Repeat Repeat 

問50

import java.util.function.BiPredicate;

public class Example {
    public static void main(String[] args) {
        BiPredicate<String, Integer> isLengthGreaterThan = (str, length) -> str.length() > length;
        System.out.println(isLengthGreaterThan.test("Lambda", 5));
        System.out.println(isLengthGreaterThan.test("Lambda", 6));
    }
}
解答
true
false

問51

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        DoubleUnaryOperator squareFunction = x -> Math.pow(x, 2);
	    System.out.println(squareFunction.apply(5.0));
    }
}
解答 コンパイルエラー
`applyAsDouble`メソッドの場合、`25.0`が出力されます。

問52

import java.util.function.Consumer;

public class Example {
    public static void main(String[] args) {
        Consumer<String> printLength = str -> System.out.println(str.length());
        printLength.accept("Example");
    }
}
解答
7

問53 ★

import java.util.Optional;
import java.util.stream.Stream;
import java.util.function.BiFunction;
import java.util.function.Predicate;

public class AdvancedExample {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Optional<Integer>> divide = (a, b) -> {
            try {
                return b != 0 ? Optional.of(a / b) : Optional.empty();
            } catch (ArithmeticException e) {
                return Optional.empty();
            }
        };

        Stream.of(42, 0, 7, 0, 21)
              .map(x -> divide.apply(84, x))
              .filter(Optional::isPresent)
              .map(Optional::get)
              .filter(isPrime())
              .forEach(System.out::println);
    }

    private static Predicate<Integer> isPrime() {
        return num -> num > 1 && Stream.iterate(2, i -> i <= Math.sqrt(num), i -> i + 1)
                                       .noneMatch(i -> num % i == 0);
    }
}

解答
2

BiFunction<Integer, Integer, Optional<Integer>> divide の定義

この関数は2つの整数を受け取り、除算を行います。
例外処理: 除算において、ゼロ除算が発生する可能性があるため、Optional.empty()を返すようにしています。
もしゼロでないなら、除算結果をOptional.of(a / b)として返します

map(x -> divide.apply(84, x)) の適用

各要素について、divide関数が適用されます。84を各要素で割り、その結果をOptionalで返します。

filter(Optional::isPresent) の適用

Optionalの値が存在するもの(Optional.of)のみを通過させます。したがって、Optional.empty()の要素は取り除かれます。
残るのはOptional.of(2), Optional.of(12), Optional.of(4)の3つです。

map(Optional::get) の適用

Optionalから値を取り出し、次に進みます。結果として2, 12, 4の3つの整数が得られます。

filter(isPrime()) の適用

自作のisPrimeメソッドで、各整数が素数かどうかを判定します。
isPrime()メソッドの動作は以下の通りです
素数は1より大きく、1とその数自身以外に約数を持たない整数です。
Stream.iterate(2, i -> i <= Math.sqrt(num), i -> i + 1).noneMatch(i -> num % i == 0);
は2からその数の平方根までの整数で割り切れるかどうかを調べます。

判定結果:

2は素数です。
12は素数ではありません。
4は素数ではありません。

結果として素数の2が出力されます。

問54

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<String, String> replaceSpaces = str -> str.replace(" ", "_");
        System.out.println(replaceSpaces.apply("Replace spaces"));
    }
}
解答
Replace_spaces
文字列 "Replace spaces" の空白をアンダースコアに置き換えて出力します。

問55

import java.util.function.Supplier;

public class Example {
    public static void main(String[] args) {
        Supplier<Boolean> trueSupplier = () -> true;
        System.out.println(trueSupplier.get());
    }
}
解答
true

問56

import java.util.function.UnaryOperator;

public class Example {
    public static void main(String[] args) {
        UnaryOperator<Integer> squareOperator = x -> x * x;
        System.out.println(squareOperator.apply(12));
    }
}
解答
144

問57

import java.util.function.Predicate;

public class Example {
    public static void main(String[] args) {
        Predicate<Integer> isEven = num -> num % 2 == 0;
        System.out.println(isEven.test(4));
        System.out.println(isEven.test(7));
    }
}
解答
true
false

問58 ★

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class AdvancedExample {
    public static void main(String[] args) {
        List<Optional<String>> strings = Arrays.asList(
                Optional.of("java"), 
                Optional.of("lambda"), 
                Optional.empty(), 
                Optional.of("stream")
        );

        Function<Optional<String>, String> processString = optStr -> optStr
                .map(str -> str.chars()
                    .filter(Character::isLetter)
                    .mapToObj(c -> (char)c)
                    .map(String::valueOf)
                    .map(String::toUpperCase)
                    .collect(Collectors.joining())
                ).orElse("EMPTY");

        List<String> result = strings.stream()
                .map(processString)
                .sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());

        result.forEach(System.out::println);
    }
}

解答
STREAM
LAMBDA
JAVA
EMPTY
`Function, String> processString` の定義

の関数は、Optionalを受け取り、文字列を処理して結果の文字列を返します
optStr.map(str -> ...) は、Optionalの値が存在する場合のみ処理を行います。

str.chars() は文字列をint型のストリームに変換します。

filter(Character::isLetter) は文字列の中からアルファベットの文字のみを抽出します。

mapToObj(c -> (char)c) は、Unicodeコードポイントをcharに変換し、文字のストリームに戻します。

map(String::valueOf) は、各charをStringに変換します。

map(String::toUpperCase) は各文字を大文字に変換します。

collect(Collectors.joining()) は、これらの大文字に変換された文字を連結し、1つの文字列にします。

最後に、Optionalが空の場合は "EMPTY" を返します。

stringsリストの各要素(Optional)をストリームに変換します。

map(processString) の適用

processString関数を各Optionalに適用し、結果の文字列を得ます。

sorted(Comparator.reverseOrder())
文字列を逆順(降順)でソートします。
出力の順序が逆順であることに注意が必要です。逆順ソートのため、アルファベット順に逆から並べられます。

問59 ★

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;

public class AdvancedExample {
    public static void main(String[] args) {
    	List<Optional<Double>> numbers = Arrays.asList(
                Optional.of(9.0), 
                Optional.empty(), 
                Optional.of(4.0), 
                Optional.of(-16.0)
            );

            Consumer<Optional<Double>> processNumber = optNum -> {
                optNum.ifPresentOrElse(
                    num -> {
                        try {
                            double sqrt = sqrt(num);
                            System.out.println( num + ": " + sqrt);
                        } catch (IllegalArgumentException e) {
                            System.out.println(num + ": " + e.getMessage());
                        }
                    }, 
                    () -> System.out.println("Empty")
                );
            };

            numbers.stream()
                   .sorted(Comparator.comparing(opt -> opt.orElse(Double.MAX_VALUE)))
                   .forEach(processNumber);
    }
    
    private static double sqrt(double num) {
        if (num < 0) {
            throw new IllegalArgumentException("Negative");
        }
        return Math.sqrt(num);
    }
}
解答
-16: Negative
4: 2
9: 3
Empty
目的: Optional のリスト内の各値を処理し、平方根を計算します。 負の値の場合はエラーメッセージを出力し、Optional が空の場合は "Empty" を出力します。

processNumber 関数: Optional型の引数を受け取り処理する。戻り値の無いConsumer。

Optional の値が存在する場合は平方根を計算し、存在しない場合は "Empty" と出力します。
負の数の場合、IllegalArgumentException をスローし、メッセージ ("Negative") を出力します。

numbers をソートし、Optional の値がないもの (空の Optional) がリストの最後に来るようにします。

問60

import java.util.function.Consumer;

public class Example {
    public static void main(String[] args) {
        Consumer<Integer> printSquare = num -> System.out.println(num * num);
        printSquare.accept(9);
    }
}
解答
81

問61

import java.util.function.Function;
import java.util.function.UnaryOperator;

public class Example {
    public static void main(String[] args) {
        UnaryOperator<Integer> square = x -> x * x;
        Function<Integer, Integer> negateAndSquare = x -> -x;
        Function<Integer, Integer> combined = square.compose(negateAndSquare);
        System.out.println(combined.apply(4));
    }
}
解答
16
`compose`はnegateAndSquare,squareの順番で処理をします。

問62

import java.util.function.BiFunction;
import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
        Function<Integer, Integer> doubleValue = x -> x * 2;
        Function<Integer, Integer> addThenDouble = doubleValue.compose(x -> add.apply(x, 3));
        System.out.println(addThenDouble.apply(5));
    }
}
解答
16

問63

import java.util.function.BiFunction;

public class Example {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> power = (base, exp) -> {
            int result = 1;
            for (int i = 0; i < exp; i++) {
                result *= base;
            }
            return result;
        };
        System.out.println(power.apply(2, 8));
    }
}
解答
256
整数 2 の 8 乗は 256 です。

問64

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<String, Integer> parseAndSquare = str -> {
            int num = Integer.parseInt(str);
            return num * num;
        };
        System.out.println(parseAndSquare.apply("7"));
    }
}
解答
49
文字列 "7" を整数に変換し、その平方は 49 です。

問65

import java.util.function.Supplier;
import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Supplier<String> stringSupplier = () -> "Hello, World!";
        Function<String, String> reverse = str -> new StringBuilder(str).reverse().toString();
        System.out.println(reverse.apply(stringSupplier.get()));
    }
}
解答
!dlroW ,olleH
"Hello, World!" を逆順にして出力します。

問66

import java.util.function.Predicate;
import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Predicate<Integer> isEven = x -> x % 2 == 0;
        Function<Integer, String> result = x -> isEven.test(x) ? "Even" : "Odd";
        System.out.println(result.apply(13));
    }
}
解答
Odd

問67

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<Integer, Integer> increment = x -> x + 1;
        Function<Integer, Integer> square = x -> x * x;
        Function<Integer, Integer> combined = increment.andThen(square);
        System.out.println(combined.apply(3));
    }
}
解答
16

問68

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<Double, String> format = x -> String.format("%.2f", x);
        Function<String, String> upperCase = String::toUpperCase;
        Function<Double, String> combined = format.andThen(upperCase);
        System.out.println(combined.apply(123.456));
    }
}
解答
123.46
数値 123.456 を小数点以下 2 桁までの文字列にフォーマットし、その結果を大文字に変換します。

問69

import java.util.function.BiFunction;
import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        BiFunction<String, Integer, String> repeat = (str, count) -> str.repeat(count);
        Function<String, Integer> length = String::length;
        BiFunction<String, Integer, Integer> combined = (str, count) -> length.apply(repeat.apply(str, count));
        System.out.println(combined.apply("Java", 3));
    }
}
解答
15
文字列 "Java" を 3 回繰り返した結果の長さは 15 です。

問70

import java.util.function.IntUnaryOperator;
import java.util.function.IntBinaryOperator;

public class Example {
    public static void main(String[] args) {
        IntUnaryOperator increment = x -> x + 1;
        IntBinaryOperator add = (a, b) -> a + b;
        IntBinaryOperator combined = (a, b) -> increment.applyAsInt(add.applyAsInt(a, b));
        System.out.println(combined.applyAsInt(4, 5));
    }
}
解答
10

問71

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<String, Integer> parseInt = Integer::parseInt;
        Function<Integer, String> toString = Object::toString;
        Function<String, String> combined = parseInt.andThen(toString);
        System.out.println(combined.apply("12345").getClass());
    }
}
解答
class java.lang.String

問72

import java.util.function.Function;
import java.util.function.Supplier;

public class Example {
    public static void main(String[] args) {
        Supplier<Integer> randomInt = () -> (int) (Math.random() * 100);
        Function<Integer, String> toHex = Integer::toHexString;
        System.out.println(toHex.apply(randomInt.get()));
    }
}
解答 ランダムに生成された整数を16進数に変換して出力します。

問73

import java.util.function.IntUnaryOperator;
import java.util.function.IntBinaryOperator;

public class Example {
    public static void main(String[] args) {
        IntUnaryOperator square = x -> x * x;
        IntBinaryOperator add = (a, b) -> a + b;
        IntUnaryOperator combined = x -> square.applyAsInt(add.applyAsInt(x, 2));
        System.out.println(combined.apply(4));
    }
}
解答
36

問74

import java.util.function.Function;
import java.util.function.UnaryOperator;

public class Example {
    public static void main(String[] args) {
        UnaryOperator<Integer> doubleValue = x -> x * 2;
        UnaryOperator<Integer> increment = x -> x + 1;
        UnaryOperator<Integer> combined = doubleValue.compose(increment);
        System.out.println(combined.apply(5));
    }
}
解答
12

問75

import

 java.util.function.BiFunction;
import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        BiFunction<Integer, Integer, Integer> multiply = (a, b) -> a * b;
        Function<Integer, Integer> addFive = x -> x + 5;
        Function<Integer, Integer> combined = addFive.andThen(x -> multiply.apply(x, 2));
        System.out.println(combined.apply(3));
    }
}
解答
16

問76

import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        Function<Integer, Integer> square = x -> Math.pow(x, 2);
        Function<Integer, Integer> half = x -> x / 2;
        Function<Integer, Integer> combined = square.andThen(half);
        System.out.println(combined.apply(6));
    }
}
解答 `Math.pow()`メソッドの戻り値はdouble型なのでコンパイルエラー

問77

import java.util.function.Function;
import java.util.function.IntUnaryOperator;

public class Example {
    public static void main(String[] args) {
        Function<Integer, Integer> triple = x -> x * 3;
        IntUnaryOperator addFive = x -> x + 5;
        Function<Integer, Integer> combined = triple.andThen(addFive::applyAsInt);
        System.out.println(combined.apply(4));
    }
}
解答
17

問78

import java.util.function.Function;
import java.util.function.IntUnaryOperator;

public class Example {
    public static void main(String[] args) {
        Function<Integer, Integer> increment = x -> x + 1;
        IntUnaryOperator square = x -> x * x;
        Function<Integer, Integer> combined = increment.andThen(square::applyAsInt);
        System.out.println(combined.apply(3));
    }
}
解答
16

問79

import java.util.function.Function;
import java.util.function.BiFunction;

public class Example {
    public static void main(String[] args) {
        BiFunction<String, Integer, String> repeat = (str, count) -> str.repeat(count);
        Function<String, Integer> length = String::length;
        Function<String, Integer> combined = str -> length.apply(repeat.apply(str, 2));
        System.out.println(combined.apply("Java"));
    }
}
解答
8
文字列 "Java" を 2 回繰り返した結果の長さは 8 です。

問80

import java.util.function.Function;
import java.util.function.UnaryOperator;

public class Example {
    public static void main(String[] args) {
        UnaryOperator<String> toUpperCase = String::toUpperCase;
        Function<String, String> trim = String::trim;
        Function<String, String> combined = toUpperCase.compose(trim);
        System.out.println(combined.apply("  hello world  "));
    }
}
解答
HELLO WORLD
文字列 " hello world " の前後の空白を削除し、その後大文字に変換します。

問81

import java.util.function.Function;
import java.util.function.IntUnaryOperator;
import java.util.function.IntBinaryOperator;

public class Example {
    public static void main(String[] args) {
        IntUnaryOperator square = x -> x * x;
        IntBinaryOperator add = (a, b) -> a + b;
        Function<Integer, Integer> combined = x -> {
            int result = add.applyAsInt(square.applyAsInt(x), 3);
            return result * result;
        };
        System.out.println(combined.apply(2));
    }
}
解答
121

問82

import java.util.function.Function;
import java.util.function.IntUnaryOperator;

public class Example {
    public static void main(String[] args) {
        Function<Integer, Integer> increment = x -> x + 1;
        IntUnaryOperator doubleAndIncrement = x -> (x * 2) + 1;
        Function<Integer, Integer> combined = increment.andThen(doubleAndIncrement::applyAsInt);
        System.out.println(combined.apply(5));
    }
}
解答
13

問83

import java.util.function.BiFunction;
import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        BiFunction<String, Integer, String> repeat = (str, count) -> str.repeat(count);
        Function<String, String> reverse = str -> new StringBuilder(str).reverse().toString();
        Function<String, String> combined = reverse.compose(str -> repeat.apply(str, 3));
        System.out.println(combined.apply("abc"));
    }
}
解答
cbacbacba

問84

import java.util.function.Function;
import java.util.function.Supplier;

public class Example {
    public static void main(String[] args) {
        Supplier<Double> randomSupplier = Math::random;
        Function<Double, String> format = x -> String.format("%.4f", x);
        Function<Double, String> combined = format.compose(randomSupplier);
        System.out.println(combined.apply(0.0));
    }
}
解答 ランダムに生成された数値を小数点以下 4 桁までの文字列にフォーマットします。

問85 ★

import java.util.*;
import java.util.function.*;

public class AdvancedExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(4, 8, null, -3);

        Function<Integer, Integer> multiply = x -> x * 3;
        IntUnaryOperator addFive = x -> x + 5;
        Function<Integer, Optional<Integer>> combined = x -> {
            try {
                return Optional.of(addFive.applyAsInt(multiply.apply(x)));
            } catch (Exception e) {
                return Optional.empty();
            }
        };

        numbers.stream()
               .map(Optional::ofNullable)
               .map(opt -> opt.flatMap(combined))
               .forEach(opt -> opt.ifPresentOrElse(
                   result -> System.out.println("Result: " + result),
                   () -> System.out.println("error!")
               ));
    }
}

解答
Result: 17
Result: 29
error!
Result: -4

combined : multiply の結果に addFive を適用し、その結果を Optional に包んで返します。例外が発生した場合は、空の Optional を返します。

map と flatMap のチェーン: リスト内の各要素に対して combined を適用し、処理結果を Optional として処理します。

各 Optional の中身を確認し、結果を出力します。もし null や例外が発生した場合は、"error!" と出力します。

問86

import java.util.function.Function;
import java.util.function.BiFunction;
import java.util.function.Supplier;

public class Example {
    public static void main(String[] args) {
        BiFunction<String, Integer, String> repeat = String::repeat;
        Function<String, Integer> length = String::length;
        Supplier<String> supplier = () -> "hello";
        Function<String, Integer> combined = str -> length.apply(repeat.apply(supplier.get(), 3));
        System.out.println(combined.apply("ignored"));
    }
}
解答
15

問87

import java.util.function.Function;
import java.util.function.IntUnaryOperator;

public class Example {
    public static void main(String[] args) {
        Function<Integer, Integer> increment = x -> x + 1;
        IntUnaryOperator square = x -> x * x;
        Function<Integer, Integer> combined = increment.andThen(square::applyAsInt);
        System.out.println(combined.apply(3));
    }
}
解答
16

問88

import java.util.function.Function;
import java.util.function.IntBinaryOperator;

public class Example {
    public static void main(String[] args) {
        IntBinaryOperator add = (a, b) -> a + b;
        Function<Integer, Integer> increment = x -> x + 1;
        Function<Integer, Integer> combined = x -> increment.apply(add.applyAsInt(x, 5));
        System.out.println(combined.apply(3));
    }
}
解答
9

問89

import java.util.function.Function;
import java.util.function.IntUnaryOperator;

public class Example {
    public static void main(String[] args) {
        Function<Integer, Integer> multiply = x -> x * 2;
        IntUnaryOperator add = x -> x + 10;
        Function<Integer, Integer> combined = multiply.andThen(add::applyAsInt);
        System.out.println(combined.apply(4));
    }
}
解答
18

問90

import java.util.function.Function;
import java.util.function.IntUnaryOperator;

public class Example {
    public static void main(String[] args) {
        IntUnaryOperator cube = x -> x * x * x;
        Function<Integer, Integer> increment = x -> x + 1;
        Function<Integer, Integer> combined = increment.andThen(cube::applyAsInt);
        System.out.println(combined.apply(2));
    }
}
解答
27

問91

import java.util.function.Function;
import java.util.function.BiFunction;
import java.util.function.Supplier;

public class Example {
    public static void main(String[] args) {
        Supplier<String> supplier = () -> "Hello, ";
        Function<String, String> appendWorld = str -> str + "World!";
        BiFunction<String, String, String> combine = (prefix, suffix) -> appendWorld.apply(prefix + suffix);
        System.out.println(combine.apply(supplier.get(), "Java"));
    }
}
解答
Hello, JavaWorld!
`Supplier`は"Hello, "を生成し、`Function`がそれに"World!"を追加します。`BiFunction`が最終的に"Hello, JavaWorld!"を生成します。

問92

import java.util.function.Function;
import java.util.function.Predicate;

public class Example {
    public static void main(String[] args) {
        Function<String, String> toUpperCase = String::toUpperCase;
        Predicate<String> containsJava = str -> str.contains("JAVA");
        Function<String, Boolean> combined = toUpperCase.andThen(containsJava::test);
        System.out.println(combined.apply("Java Programming"));
    }
}
解答
true
`Function`が文字列を大文字に変換し、その結果に対して`Predicate`が"JAVA"を含むかをチェックします。

問93

import java.util.function.Function;
import java.util.function.IntUnaryOperator;

public class Example {
    public static void main(String[] args) {
        Function<String, Integer> length = String::length;
        IntUnaryOperator doubleValue = x -> x * 2;
        Function<String, Integer> combined = str -> doubleValue.applyAsInt(length.apply(str));
        System.out.println(combined.apply("Hello"));
    }
}
解答
10

問94

import java.util.function.BiFunction;
import java.util.function.Function;

public class Example {
    public static void main(String[] args) {
        BiFunction<String, Integer, String> repeatString = (str, times) -> str.repeat(times);
        Function<String, String> addPrefix = str -> "Prefix: " + str;
        Function<String, String> combined = addPrefix.andThen(s -> repeatString.apply(s, 2));
        System.out.println(combined.apply("Hello"));
    }
}
解答
Prefix: HelloPrefix: Hello
`Function`が文字列に"Prefix: "を追加し、`BiFunction`がその文字列を2回繰り返します。

問95

import java.util.function.Function;
import java.util.function.Supplier;
import java.util.function.Consumer;

public class Example {
    public static void main(String[] args) {
        Supplier<String> supplier = () -> "Stream API";
        Function<String, String> toUpperCase = String::toUpperCase;
        Consumer<String> printConsumer = System.out::println;
        printConsumer.accept(toUpperCase.apply(supplier.get()));
    }
}
解答
STREAM API

問96

import java.util.function.Function;
import java.util.function.IntUnaryOperator;

public class Example {
    public static void main(String[] args) {
        Function<Integer, Integer> addFive = x -> x + 5;
        IntUnaryOperator multiplyBy = x -> x * 2;
        Function<Integer, Integer> combined = addFive.andThen(multiplyBy::applyAsInt);
        System.out.println(combined.apply(3));
    }
}
解答
16

問97

import java.util.function.Function;
import java.util.function.Supplier;

public class Example {
    public static void main(String[] args) {
        Supplier<String> supplier = () -> "Data";
        Function<String, String> process = str -> "Processed " + str;
        Function<Supplier<String>, String> combined = s -> process.apply(s.get());
        System.out.println(combined.apply(supplier));
    }
}
解答
Processed Data
`Supplier`が"Data"を提供し、`Function`がその文字列に"Processed "を追加します。

問98 ★

import java.util.Optional;
import java.util.function.BiFunction;
import java.util.function.Function;

public class TestCollection {

	public static void main(String[] args) {

		BiFunction<String, Integer, Optional<String>> safeFormatMessage = (name, count) -> {
            try {
                if (count < 0) throw new IllegalArgumentException("negative");
                return Optional.of(String.format("Hello %s, you have %d messages", name, count));
            } catch (Exception e) {
                return Optional.empty();
            }
        };

        Function<Optional<String>, String> addGreeting = opt -> 
            opt.map(str -> "Greeting: " + str)
               .orElse("error");

        BiFunction<String, Integer, String> combined = (name, num)
        				-> addGreeting.apply(safeFormatMessage.apply(name, num));

        System.out.println(combined.apply("Alice", 0));
        System.out.println(combined.apply("Bob", -1));
	}
}
解答
Greeting: Hello Alice, you have 5 messages
error
名前とメッセージ数を combined に渡す。

safeFormatMessage でメッセージを生成する(または失敗する)。

生成されたメッセージに "Greeting: " を付けて返す、または失敗時に "error" を返す。

問99 ★

import java.util.function.Function;
import java.util.function.BiFunction;

public class Example {
    public static void main(String[] args) {
    	 Function<String, Optional<Integer>> safeLength = str -> {
             try {
                 if (str == null) throw new IllegalArgumentException("null");
                 return Optional.of(str.length());
             } catch (Exception e) {
                 return Optional.empty();
             }
         };

         BiFunction<String, Integer, Optional<Boolean>> safeIsLengthEqual = (str, len) -> {
             try {
                 return Optional.ofNullable(str)
                                .flatMap(safeLength)
                                .map(length -> length.equals(len));
             } catch (Exception e) {
                 return Optional.empty();
             }
         };

         Function<String, String> combined = str -> 
             safeIsLengthEqual.apply(str, 5)
                              .map(equal -> equal ? "correct" : "incorrect")
                              .orElse("error");

         System.out.println(combined.apply("Hello"));
         System.out.println(combined.apply("World!"));
         System.out.println(combined.apply(null));
    }
}
解答
correct
incorrect
error
safeLength: 入力文字列の長さを取得します。文字列が null の場合、空の Optional を返します。

safeIsLengthEqual: 文字列の長さが指定した長さと等しいかを確認します。null や例外の場合には空の Optional を返します。

combined: 長さが指定値と一致するかどうかをチェックし、結果に応じたメッセージを返します。エラーが発生した場合にはエラーメッセージを返します。

問100 ★

import java.util.function.Function;
import java.util.function.IntUnaryOperator;

public class Example {
    public static void main(String[] args) {
        Function<Integer, Integer> safeSquare = x -> {
            if (x < 0) throw new IllegalArgumentException("Negative input");
            return x * x;
        };

        IntUnaryOperator safeTriple = x -> {
            if (x < 0) throw new IllegalArgumentException("Negative input");
            return x * 3;
        };

        Function<Integer, Optional<Integer>> combined = x -> {
            try {
                int tripled = safeTriple.applyAsInt(x);
                return Optional.of(safeSquare.apply(tripled));
            } catch (Exception e) {
                return Optional.empty();
            }
        };

        System.out.println(combined.apply(2).orElse(-1));
        System.out.println(combined.apply(-2).orElse(-1));
    }
}
解答
36
-1
safeSquare: 入力値の平方を計算します。入力が負の場合、IllegalArgumentException をスローします。

safeTriple: 入力値を3倍にします。入力が負の場合、IllegalArgumentException をスローします。

combined: 入力値に対して、まず safeTriple で3倍にし、その結果に safeSquare を適用します。例外が発生した場合は空の Optional を返します。

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?