Java lambda表达式汇总

本文介绍 Java 中 Stream API 的多种实用技巧,包括排序、分组、过滤等操作,以及如何利用这些功能提升代码效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

顺序流和并行流
//顺序流   List <Person> people = list.Stream.collect(Collectors.toList());
//并行流   List <Person> people = list.Stream.parallel().collect(Collectors.toList());
使用顺序方式去遍历时,每个item读完后再读下一个item
使用并行去遍历时,数组会被分成多个段,其中每一个都在不同的线程中处理,然后将结果一起输出

获取流
集合  Stream<Person> stream = list.stream();

数组  String[] names = {"chaimm","peter","john"};
      Stream<String> stream = Arrays.stream(names);

直接将几个值变成流对象
Stream<String> stream = Stream.of("chaimm","peter","john");

文件
try(Stream lines = Files.lines(Paths.get("文件路径名"), Charset.defaultCharset())){
 //可对lines做一些操作
}

1、List集合的排序 
list.sort((o1, o2) -> o1.value - o2.value);
eg: list.sort(int o1, int o2) -> o1-o2);   o1-o2的结果大于0降序,等于0不变,小于0升序

2、集合的分组
(1) 结果将会以Object的某个属性值分组,每个组的结果放在一个List中,最后整体记过放在一个map中
    eg: Map<Integer, List<Object>> maps = list .stream().collect(Collectors.groupingBy(Object::get方法名字, Collectors.toList()));
    Collectors.toList() 可以换成 Collectors.toSet()

(2) 分组将实体属性值作为key,另一个属性值作为value
    eg: oesList.stream().collect(Collectors.groupingBy(OrgEmpSysId::getSystemType, Collectors.mapping(OrgEmpSysId::getOrgId, Collectors.toList())));

(3) 分组将实体属性值作为key,value值可再一次map
    eg: oesList.stream().collect(Collectors.groupingBy(OrgEmpSysId::getSystemType, Collectors.mapping(T -> { return "转换后的对象";}, Collectors.toList())));

(4) 根据某个属性分组计数
    eg: Map<String, Long> result1 = list1.stream().collect(Collectors.groupingBy(Student::getGroupId, Collectors.counting()));

(5) 根据整个实体对象分组计数,当其为String时常使用
    eg: Map<String, Long> result2 = list1.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); 

(6) 根据分组的key值对结果进行排序、放进另一个map中并输出 Map<String,Long> xMap=new HashMap<>();
    eg:  result1.entrySet().stream().sorted(Map.Entry.<String,Long>comparingByKey().reversed()) //reversed不生效 .forEachOrdered(x->xMap.put(x.getKey(),x.getValue())); System.out.println(xMap);

(7) 分组,并统计其中一个属性值得sum或者avg:id总和
    eg: Map<String,Integer> result3=list1.stream().collect( Collectors.groupingBy(Student::getGroupId,Collectors.summingInt(Student::getId)) );

根据连续属性分组
(1) eg: orgEmpSysList.parallelStream().collect(Collectors.groupingBy(((Function<OrgEmpSys, OrgEmpSysId>) OrgEmpSys::getId).andThen(OrgEmpSysId::getSystemType)));

(2) eg: list.stream().collect(Collectors.toMap(((Function<RoleToEmp, RoleToEmpId>)RoleToEmp::getId).andThen(RoleToEmpId::getRoleId), ((Function<RoleToEmp, Role>)RoleToEmp::getRole).andThen(Role::getRoleName)));

(3) 添加解决重复key问题(key1, key2) -> key2
 eg: list.stream().collect(Collectors.toMap(((Function<RoleToEmp, RoleToEmpId>)RoleToEmp::getId).andThen(RoleToEmpId::getRoleId), ((Function<RoleToEmp, Role>)RoleToEmp::getRole).andThen(Role::getRoleName), (key1, key2) -> key2));

3、List集合转数组
List<ChatroomParam> chatroomParamList = param.getChatroomParams();
ChatRoomInfo[] chatroomCreateChatRoomInfo = chatroomParamList .stream().map(c -> {
      ChatRoomInfo chatRoomInfo =  new ChatRoomInfo(c .getChatroomId(), c .getChatroomName());
      return chatRoomInfo;
}).toArray(ChatRoomInfo[]:: new );

4、List转map
(1) key为对象属性,value也为对象属性
    eg1: accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
(2) key为对象属性,对象本身作为value
    eg1: accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
    eg2: accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
(3) 重复key的问题解决
    accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
(4) 指定生成的Map集合的类型, 如生成的Map是一个LinkedHashMap
    accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));

5、filter使用
    Stream map = persons.stream().filter(p -> p.getAge() > 18).map(person -> new Adult(person));

6、count统计
    int count = persons.stream().filter(p -> p.getAge() > 18) .map(person -> new Adult(person)).count();

7、 Collect(收集流的结果)
    List adultList= persons.stream().filter(p -> p.getAge() > 18).map(person -> new Adult(person)).collect(Collectors.toList());

8、limit(截断)
    对一个Stream进行截断操作,获取其前N个元素,如果原Stream中包含的元素个数小于N,那就获取其所有的元素

9、distinct(去重)
    对于Stream中包含的元素进行去重操作(去重逻辑依赖元素的equals方法),新生成的Stream中没有重复的元素

10、skip(跳过流前面的n个元素)
    list.stream().skip(3).collect(Collectors.toList());

11、flatMap合并流
    对Stream中的元素进行类似Map的操作,这个元素应该是集合或数组类型
    eg1: String s = "a;c;d;f;r;g;h;j;k;l";
    List<String> list = Arrays.asList(s).stream().map(S -> S.split(";")).flatMap(S ->                         Arrays.stream(S)).collect(Collectors.toList());
    上面flatMap中的S是一个数组,进行flatMap操作可以将数组中的每个元素单独放到主Stream中,若不进行flatMap操作,则得到的是List<String[]>集合
    eg2: list.stream().map(line->line.split(" ")).flagmap(Arrays::stream);

12、排序
    list.stream().sorted((p1, p2) -> p1.getSeq()- p2.getSeq()).collect(Collectors.toList());
         注意:p1.getSeq()- p2.getSeq() 是升序, p2.getSeq()- p1.getSeq()是降序

12、元素匹配
    (1) 是否匹配任一元素:anyMatch
        anyMatch用于判断流中是否存在至少一个元素满足指定的条件,这个判断条件通过Lambda表达式传递给anyMatch,执行结果为boolean类型。
    如,判断list中是否有学生:
    eg: boolean result = list.stream().anyMatch(Person::isStudent);

    (2) 是否匹配所有元素:allMatch
        allMatch用于判断流中的所有元素是否都满足指定条件,这个判断条件通过Lambda表达式传递给anyMatch,执行结果为boolean类型。
    如,判断是否所有人都是学生:
    eg: boolean result = list.stream().allMatch(Person::isStudent);

    (3) 是否未匹配所有元素:noneMatch
        noneMatch与allMatch恰恰相反,它用于判断流中的所有元素是否都不满足指定条件:
    eg: boolean result = list.stream().noneMatch(Person::isStudent);

    (4) 获取任一元素findAny
    findAny能够从流中随便选一个元素出来,它返回一个Optional类型的元素。

    Optional<Person> person = list.stream().findAny();







评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值