java 8 lamda表达式

源上的一系列操作,其中操作包括中间操作和终端操作
中间操作如filter、maptoint
终端操作如count ,sum,foreach

创建流
Stream.of()
Stream.builder()
Stream.generate()

  1. boolean allMatch(Predicate<? super T> predicate)
    返回此流的所有元素是否与提供的谓词匹配。
    @Test
    public void testStreamAllMatch() {
    boolean flag = Stream.of(1, 2, 3).allMatch(item -> item == 1); //false
    flag = Stream.of(1, 2, 3).allMatch(item -> item < 4); //true
    }
    2.boolean anyMatch(Predicate<? super T> predicate)
    返回此流的任意一个元素是否与提供的谓词匹配。(一个匹配即可)
    @Test
    public void testStreamAnyMatch() {
    boolean flag = Stream.of(1, 2, 3).anyMatch(item -> item == 1);
    System.out.println(flag) //true
    flag = Stream.of(1, 2, 3).anyMatch(item -> item < 1);
    System.out.println(flag); //false
    }
    3.collect(Collector<? super T,A,R> collector)
    collect(Supplier supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)
    @Test
    public void testStreamCollect() {
    List list = Stream.of(1,2,3,4).collect(Collectors.toList());
    Set set = Stream.of(1,2,3,4).collect(Collectors.toSet());
    /**

    • 主键不能有重复
      /
      Map<Integer, Integer> map = Stream.of(1,2,3,4).collect(Collectors.toMap(item->item,item->item+1)); //<1,2><2,3><3,4><4,5>
      /
      *
    • 主键重复时抛出异常
      */
      try {
      map = Stream.of(1,1,3,4).collect(Collectors.toMap(item->item,item->item+1));
      } catch (Exception e) {
      e.printStackTrace();
      //java.lang.IllegalStateException: Duplicate key 2
      }

    /**

    • 主键重复时,取值策略,本例是取新值
      */
      map = Stream.of(1,1,3,4).collect(Collectors.toMap(item->item,item->item+1,(oldValue,newValue)->newValue));
      System.out.println(map);
      }

4.filter(Predicate<? super T> predicate)
返回由与此给定谓词匹配的此流的元素组成的流。
@Test
public void tsetStreamFilter() {
//filter过滤大于1的元素,distinct取不重复的元素,limit取前4个元素,count取数量
Stream.of(1,2,3,4,4,5,6,7,8).filter(item->item>1).distinct().limit(4).count();
}
5.sorted(Comparator<? super T> comparator)
sorted()

@Test
public void testStreamSorted() {
//指定排序规则
List list = Stream.of(1,4,3,5).sorted(new Comparator() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
}).collect(Collectors.toList()); //(1,3,4,5)

//自然排序规则
list = Stream.of(1,4,3,5).sorted().collect(Collectors.toList()); (1,3,4,5)
}
reference:http://www.matools.com/api/java8

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值