Ya10
@Ya10

Как с помощью Predicate использовать сортировку в масиве?

Собственно вот само задание:
1) Add in a Main class a sumEven() static method that takes two parameters: the first - an array of integers, and the second - the predicate of Predicate type for selecting numbers.
2) Add in a main() method code that invokes sumEven() method and in the form of a lambda expression specifies the selection condition the values of the array elements.
3) Add in a Main class a printJStr() static method that takes two parameters: the first - an list of strings, and the second - the predicate of Predicate type for the selection of strings beginning with a given letter.
4) Add in a main() method code that invokes printJStr() method and in the form of a lambda expression specifies the selection condition the strings.


Умом понимаю, что должно быть, чтото на подобии этого:
static void sumEven(int[] a, Predicate<Integer> b) {
        Arrays.stream(a)
                .sorted((x, y) -> Integer.compare(x, y))
                .toArray(Integer[]::new);
        System.out.print(Arrays.toString(a));
    }

    static void printJStr(String[] str, Predicate<String> b) {

        Arrays.stream(str).sorted((Comparator<? super String>) b).forEach(System.out::println);
    }

но не сходиться нихрена, да и Я не совсем понимаю, по какому критерию сортировать?
  • Вопрос задан
  • 102 просмотра
Пригласить эксперта
Ответы на вопрос 2
xez
@xez Куратор тега Java
TL Junior Roo
Никак. Predicate используется в Stream<T> filter(Predicate<? super T> predicate);
Ответ написан
@kpechenenko
Никак.

А зачем вам сортировать массив в данной задаче?

Исходя из формулировки прикрепленного задания решение может выглядеть следующим образом:
public class Main {
    private static int sumEven(int[] values, Predicate<Integer> test) {
        return Arrays.stream(values)
                .filter(test::test)
                .sum();
    }

    public static void main(String[] args) {
        int[] values = {1, 2, 3, 4, 5, 6, 7, 8};
        int sumOfEvenValues = Main.sumEven(values, x -> x % 2 == 0);
        System.out.println("Sum of even is " + sumOfEvenValues);
        List<String> strings = List.of(
                "JUG",
                "JPoint",
                "PyConf",
                "Joker"
        );
        Main.printJStr(strings, s -> s.startsWith("J"));
    }

    private static void printJStr(List<String> strings, Predicate<String> test) {
        strings.stream()
                .filter(test)
                .forEach(System.out::println);
    }
}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы