当前位置: 代码迷 >> 综合 >> Java8 Lambda表达式常见应用场景(了解-中等)
  详细解决方案

Java8 Lambda表达式常见应用场景(了解-中等)

热度:2   发布时间:2024-02-20 17:23:17.0
  • 集合的使用
  •  代替 Runnable  
  • Predicate 条件过滤
  • Map 映射
  • Reduce 聚合

集合的使用

  • 集合的遍历
  •  List转为Map
  •  将List分组
  •  集合过滤
  • 集合求和

集合的遍历

public class User{private String name;private int age;private String sex;public User (String name, int age,String sex){supper();this.name = name;this.age = age;this.sex = sex;}@Overridepublic String toString(){return "User [name="+name+",age="+age+",sex="+sex+"]";} 
//数组的遍历
List<Integer> number = Arrays.asList(1,2,3,4,5);
//Lambda 列表表达式
numbers.forEach(x -> System.out.println(x));
//方法引用列表迭代
number.stream().forEach(System.out::println);//初始化集合
List<User> userList = new ArrayList<User.();
userList.add(new User("赵云",23,"男"));
userList.add(new User("张飞",24,"男"));
userList.add(new User("吕布",22,"男"));
userList.add(new User("文松"27,"男"));
userList.add(new User("欣兴"26,"男"));//遍历集合Lambda
userList.stream().forEach(user->{System.out.println(user);
});//遍历集合,方法引用
userList.stream().forEach(System.out::println);

集合的其他使用

//List转Map key为Name
Map<String,User> userMap = userList.stream().collect(Collectors.toMap(User::getName,a->a,(k1,k2)->k1));
System.out.println(userMap);//根据性别分组
Map<String,List<User>> groupBy = userList.stream().collect(Collectors.groupingBy(User::getSex));
System.out.println(groupBy);//取出性别为男的用户
List<User> filterList = userList.stream().filter(User->user.getSex().equals("男").collect(Collectors.toList());filterList.stream().forEach(user->{System.out.println(user.getName());});//统计性别为女的年龄的和
int totalAge =userList.stream().filter(user->user.getSex().equals("女")).mapToInt(User::getAge).sum();
System.out.println("性别为女的人的年龄和是:"+totalAge);

代替 Runnable

//利用lambda实现Runnable里的run方法
Runnable r = () ->{System.out.println(Thread.currentThread().getName()):};
for(int i=1;i<=100;i++){Thread t = new Thread(r);t.start();
}
for(int i =1;i<=100;i++){//线程池ExecutorService executorService = Executors.newFixedThreadPool(3);//利用lambda实现Runnable里的run方法executorService.execute(()->{System.out.println(Thread.currentThread().getName());});executorService.shutdown();
}

Predicate 条件过滤

使用 Predicate 接口,将相同的处理逻辑封装到 filter 方法中,重复调用:

public static void main(String[] args){List<Integer> numbers = Arrays.asList(1,2,3,4,5);List<String> words = Arrays.asList("a","b","c");//复用filter(numbers,x->(int)x%2 == 0);filter(words,x-> ((String)x).length()>1);
}/**
*过滤List
*/
public static void filter(List list,Predicate condition){list.forEach(x->{if(condition.test(x)){System.out.println(x);}});
}

Map 映射和Reduce 聚合

List<Integer> numbers = Arrays.asList(1,2,3,4,5);
//原来的值乘以2再放入新的列表
List<Integer> mapped = numbers.stream().map(x->x*2).collect(Collectors.toList()):
mapped.forEach(System.out::println);List<Integer> numbers2 =Arrays.asList(1,2,3,4,5);
//得到所有元素聚合后的值
int sum = numbers2.stream().reduce((x,y)->x+y).get();
System.out.println(sum);