Java8语法

2021-11-23  本文已影响0人  超音速6

转换成List

@Test
public void t1(){
    List<String> list = Stream.of("1", "2", "3").collect(Collectors.toList());
    list.forEach(System.out::println);
}

转换成Set

@Test
public void t2(){
    Set<String> collect = Stream.of("1", "2", "3").collect(Collectors.toSet());
    collect.forEach(System.out::println);
}

转换成其他集合,比如TreeSet

@Test
public void t3(){
    TreeSet<String> collect = Stream.of("1", "2", "3").collect(Collectors.toCollection(TreeSet::new));
    collect.forEach(System.out::println);
}

计算平均值

@Test
public void t4() {
    Double collect = Stream.of("1", "2", "3").collect(Collectors.averagingInt(n -> Integer.parseInt(n)));
    System.out.println(collect);

    Double collect = Stream.of("1", "2", "3").collect(Collectors.averagingInt(Integer::parseInt));
    System.out.println(collect);
}
上一篇 下一篇

猜你喜欢

热点阅读