collection 与stream与lambd表达式的结合使用

本文详细介绍了ArrayList的高级操作方法,如forEach、sort、stream等,并通过实例讲解了如何结合Lambda表达式进行高效编程。同时,文章还涵盖了Consumer、Comparator、Predicate等接口的Lambda表达式实现。

Arraylist除了常用的add,get,set,remove,contains,size,indexof,sublist这些常用的增删改方法,还有已下

1、void java.util.ArrayList.forEach(Consumer<? super String> action)
Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Unless otherwise specified by the implementing class, actions are performed in the order of iteration (if an iteration order is specified). Exceptions thrown by the action are relayed to the caller
 
对list中的元素,遍历执行action

 

2、void java.util.ArrayList.sort(Comparator<? super String> c)

Sorts this list according to the order induced by the specified Comparator

按照comparator的compare指定的排序规则。排序集合中内容

New Comparator<String>(){

@Override  //重写compare方法的实现(正数,0,负数分别对应大于,等于,小于)

          public int compare(String s1, String s2) { 

              return (s1.compareTo(s2)); //按字典顺序比较两个字符串character,字典顺序越往后的index越大。Eg: “a”.compareTo(“c”):-2; “a”.compareTo(“ab”):-1; “d”.compareTo(“ab”): 3;

 

              }}

3、Stream<String> java.util.Collection.stream()
Returns a sequential Stream with this collection as its source
4、Stream<String> java.util.stream.Stream.filter(Predicate<? super String> predicate)

Returns a stream consisting of the elements of this stream that match the given predicate.

过滤出符合这些predicate条件的集合

Eg: Stream.filter((p) -> (p.getSalary() > 1400))  就是过滤出这些工资大于1400的数据

sorted(Comparator<? super T> comparator)

min(Comparator<? super T> comparator)

max(Comparator<? super T> comparator);

limit(long maxSize);

 

截止以上我们对集合以及stream的一些常用用法有了个大概的了解。下面我们再来学习下,如何结合lambda表达式来使用这些常用的集合以及stream的方法。

1、首先了解下什么是lambda表达式

Lambda表达式的语法

基本语法:

 (parameters) -> expression

(parameters) ->{ statements; }

 

下面是Java lambda表达式的简单例子:

   // 1. 不需要参数,返回值为 5 

( ) -> 5 

   // 2. 接收一个参数(数字类型),返回其2倍的值 

x -> 2 * x 

   // 3. 接受2个参数(数字),并返回他们的差值 

(x, y) -> x – y 

   // 4. 接收2个int型整数,返回他们的和 

(int x, int y) -> x + y 

   // 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void) 

(String s) -> System.out.print(s)

 

2、可以使用lambda表达式,代替实现ConsumerComparatorPredicate等对象

1)  lambda表达式,代替实现Consumer

arraylist.foreach(p->p+2)

 

2)  lambda表达式,代替实现Comparator

Array.sort(arraylist, New Comparator<String>(){ public int compare(String s1, String s2) {                return (s1.compareTo(s2));        }}

)

替换成

Array.sort(arraylist,(s1,s2)->(s1.compareTo(s2)));

     3) lambda表达式,代替实现Predicate

phpProgrammers.stream().filter((p) -> (p.getSalary() > 1400)) 

转载于:https://www.cnblogs.com/happyliuyi/p/10966419.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值