java8 lambda表达式和stream流学习笔记

供自己以后查阅

https://cloud.tencent.com/developer/article/1187833

https://blog.csdn.net/yinhaoh/article/details/104674883/

https://www.jianshu.com/p/9f34edcbe817

 

java8中Collectors的方法使用实例

https://blog.csdn.net/u014231523/article/details/102535902

不错的博

 例子 user类


	// stream().forEach()遍历集合
	list.stream().forEach(user->{System.out.println(user.getId());});

	//分组
	// Collectors.groupingBy(User::getSex)其实是Collectors.groupingBy(User::getSex,Collectors.toList())的缩写,还可以计算count求和等
	Map> groupByCity = userList.stream().collect(Collectors.groupingBy(User::getSex));
	
	//遍历分组
	for (Map.Entry> entryUser : groupBySex.entrySet()) {
    	String key = entryUser.getKey();
    	List entryUserList = entryUser.getValue();
	}

	// 多分组字段
	// 字段写入
	Function> compositeKey = f -> Arrays.asList(f.getAge(), f.getSex(), f.getName());
	// 分组
	Map> map = userList.stream().collect(Collectors.groupingBy(compositeKey, Collectors.toList()));
	//遍历分组
	for (Map.Entry> entryUser : map.entrySet()) {
 	    List key = (List) entryUser.getKey();
  	    Integer age= (Integer) key.get(0);
  	    String sex=  key.get(1).toString() ;
  	    String name=  key.get(2).toString();
   	    List entryUserList = entryUser.getValue();
 	}
        
	//排序
	//根据字段排序
	userList = userList.sort(Comparator.comparing(User::getId));
	//多字段排序,根年龄、性别排序
	userList = userList.sort(Comparator.comparing(User::getAge).thenComparing(User::getSex));
	
	//某字段去重
	userList = userList.stream().map(x->x.getName()).distinct().collect(Collectors.toList());
	
	//过滤
	userList = userList.stream().filter(x->StringUtils.isNotEmpty(x.getName()))..collect(Collectors.toList());

	//求和
	int sumAge = userList.stream().mapToInt(User::getAge).sum();
	BigDecimal totalQuantity = userList.stream().map(User::getWeight).reduce(BigDecimal.ZERO, BigDecimal::add);
	
	//最值
	//最小
	Integer minAge = userList.stream().map(User::getAge).min(Integer::compareTo).get();
	//最大
	Integer maxAge = userList.stream().map(User::getAge).max(Integer::compareTo).get();
	
	// 赋相同值
	userList.stream().forEach(a -> a.setAge(17));

	// foreach
	userList.forEach(s -> System.out.println(s.getId()));
	// lambda分页
		
	List result = userList.stream().skip(pageSize * (pageIndex - 1)).limit(pageSize).collect(Collectors.toList());
 
  

   

public class User {
	
	private Integer id ;
	private String name ;
	private String sex;
	private Integer age;
	private BigDecimal weight;
	public void setId(Integer id){
		this.id = id;
	}
	public Integer getId(){
		return this.id;
	}
	public void setSex(String sex){
		this.sex= sex;
	}

	public String getSex(){
		return this.sex;
	}

	public void setName(String name){
		this.name = name;
	}

	public String getName(){
		return this.name;
	}
	
	public void setAge(Integer age){
		this.age = age
	}
	public Integer getAge(){
		return this.age;
	}
	
	public void setWeight(String weight){
		this.weight = weight;
	}

	public String getWeight(){
		return this.weight;
	}


 

你可能感兴趣的:(java,lambda,stream,java8)