stream学习


public class StreamTest {

public static void main(String[] args)  {
    Random random = new Random();
    System.out.println("===使用forEach打印5个随机数并排序===");
    random.ints().limit(5).sorted().forEach(System.out::println);
    System.out.println("========================================");

    List<Integer> numbers = Arrays.asList(9,1,2,3,7,8,5);
    System.out.println("===使用sorted降序排列====默认升序===");
    List<Integer> sortedList = numbers.stream().sorted(Comparator.comparingInt(Integer::intValue).reversed()).collect(Collectors.toList());
    System.out.println(sortedList);
    System.out.println("========================================");

    System.out.println("===使用map将计算元素的结果映射到结果集===");
    List<Integer> squaresList = numbers.stream().map(i -> i*(i+1)).collect(Collectors.toList());
    System.out.println(squaresList);
    System.out.println("========================================");


    List<String> strList = Arrays.asList("asd","","dgf","","fghh","asd","dgf");

    System.out.println("===使用filter将List中不为空的元素放到另一个List中====");
    List<String> filterList = strList.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
    System.out.println(filterList);
    System.out.println("========================================");


    System.out.println("===使用filter将List中不为空的元素放到String中以“;”分割====");
    String filterString = strList.stream().filter(s -> !s.isEmpty()).collect(Collectors.joining(";"));
    System.out.println(filterString);
    System.out.println("========================================");

    System.out.println("===使用filter计算List中元素相同的个数====");
    Map<String,Integer> map=new HashMap<>();
    for (String str:
         strList) {
        int count = (int) strList.stream().filter(s -> s.equals(str)).count();
        if(!map.containsKey(str)&&!"".equals(str)){
            map.put(str,count);
        }else{
            map.put("空字符",count);
        }

    }
    Set<Map.Entry<String,Integer>> entry = map.entrySet();
    Iterator<Map.Entry<String,Integer>> iterator = entry.iterator();
    while(iterator.hasNext()){
        Map.Entry<String,Integer> next = iterator.next();
        System.out.println(next);
    }
    System.out.println("========================================");
}

}
打印结果如下:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值