lambda表达式


@Test
public void lambda1(){
//遍历
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
list.forEach(key->{
if (key > 1) {
System.out.println(key);
}
});
}
@Test
public void lambda2(){
Predicate<Integer> pre1 = (i)->i>1;
Predicate<Integer> pre2 = (i)->i<4;
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
//过滤
list.stream().filter(t -> pre1.and(pre2).test(t)).collect(Collectors.toList()).forEach(System.out::println);
}
@Test
public void lambda3(){
Predicate<Integer> pre1 = (i)->i>1;
Predicate<Integer> pre2 = (i)->i<4;
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
//排序
list.stream().sorted((t1, t2) -> t1.compareTo(t2)).collect(Collectors.toList());
//分页
list.stream().skip(2).limit(1).collect(Collectors.toList());
//去重
list.stream().distinct().collect(Collectors.toList());
//最大值
list.stream().max((t1, t2) -> t1.compareTo(t2)).get();
//最小值
list.stream().min((t1, t2) -> t1.compareTo(t2)).get();
//list中的元素是否全部满足predicate
list.stream().allMatch(t -> pre1.test(t));
//list中的元素是否有一个满足predicate
list.stream().anyMatch(t -> pre1.test(t));
//list中的元素是否全部不满足predicate
list.stream().noneMatch(t -> pre1.test(t));
//将list中的元素+1
list.stream().map(t -> t + 1).collect(Collectors.toList());
//map reduce 将list中的元素+1并求和
list.stream().map(t -> t + 1).reduce((sum, s) -> sum + s).get();
}
@Test
public void lambda(){
List<Integer> list1 = Arrays.asList(9, 1, 0,0);
List<Integer> list2 = Arrays.asList(70, 0,0,0);
//求max min sum average
IntSummaryStatistics intSummaryStatistics1 = list1.stream().
mapToInt(x -> x).summaryStatistics();
IntSummaryStatistics intSummaryStatistics2 = list2.stream().
mapToInt(x -> x).summaryStatistics();
//将结果1和结果2合并求max和min以及averrge
intSummaryStatistics1.combine(intSummaryStatistics2);
long sum = intSummaryStatistics1.getSum();
int max = intSummaryStatistics1.getMax();
int min = intSummaryStatistics1.getMin();
double average = intSummaryStatistics1.getAverage();
System.out.println(max + ":" + min + ":" + average);
}

对象和对象的方法


posted @ 2017-12-11 17:54  奋小斗g  阅读(204)  评论(0编辑  收藏  举报