Java list stream 常用方法

发布于:2024-07-03 ⋅ 阅读:(14) ⋅ 点赞:(0)

Sorted

根据字符长短排序

public class Java8Demo1 {

    public static void main(String[] args) {

        // Sort by length of the words.
        List<String> list = Arrays.asList("1234","456","abefc");

        List<String> list1 = list.stream()
                .sorted(Comparator.comparing(x -> x.length()))
                .collect(Collectors.toList());
        list1.forEach(l -> {
            System.out.println(l);
        });

        //lambda
        List<String> list2 = list.stream()
                .sorted((l1, l2) -> l1.length() - l2.length())
                .collect(Collectors.toList());
        list2.forEach(l -> {
            System.out.println(l);
        });
    }
}

BiFunction example

public class Java8Demo1 {

    public static void main(String[] args) {
        // Try BiFunction
        MyCalculator<Double> calculator = new MyCalculator();

        // +
        System.out.println(calculator.compute(2.0, 3.0, (a, b) -> a + b));

        // -
        System.out.println(calculator.compute(21.0, 3.0, (a, b) -> a - b));

        // *
        System.out.println(calculator.compute(2.0, 3.0, (a, b) -> a * b));

        // /
        System.out.println(calculator.compute(6.0, 3.0, (a, b) -> a / b));
    }
}

class MyCalculator<T> {
    public T compute(T t1, T t2, BiFunction<T,T,T> function) {
        return function.apply(t1, t2);
    }
}

输出

5.0
18.0
6.0
2.0

Process finished with exit code 0

网站公告

今日签到

点亮在社区的每一天
去签到