当前位置:   article > 正文

Java list stream 常用方法

Java list stream 常用方法

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);
        });
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

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);
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

输出

5.0
18.0
6.0
2.0

Process finished with exit code 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/795432
推荐阅读
相关标签
  

闽ICP备14008679号