list.stream()基本应用

参考 ianly梁炎 url:https://blog.csdn.net/ianly123/article/details/82658622

1、String中某个字符出现次数:

    public static int strCount(String str,String findByStr){
        String[] split = str.split("");
        return Arrays.asList(split).stream().filter(s -> s.equals(findByStr)).collect(Collectors.toList()).size();
    }

2、List去除重复元素:

    public static List removeRepEle(List list){
        return list.stream().distinct().collect(Collectors.toList());
    }

eg:Object 对象

package com.ouyeel.platform.components.rzcore.foundation.service.csy.vo;
import java.io.Serializable;
/**Object对象*/
public class PaFlowInfo implements Serializable {
    private static final long serialVersionUID = 1L;
    private String serialNo;
    private String remark;
    public String getSerialNo() {
        return serialNo;
    }
    public void setSerialNo(String serialNo) {
        this.serialNo = serialNo;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
}

3、List筛选符合条件的对象

public static List getConditionList(Listlist){
           return list.stream().filter(paFlowInfo->paFlowInfo.getSerialNo().equals("serialNo_1")).collect(Collectors.toList());
       }

4、List根据对象属性(一个),去除重复对象

public static List removeRepEleByOne(List list){
           return list.stream().collect(
                   Collectors.collectingAndThen(
                           Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(PaFlowInfo::getSerialNo))), ArrayList::new)
           );
       }

5、List根据对象属性(两个),去除重复对象

public static List removeRepEleByTwo(List list){
        return list.stream().collect(
                Collectors. collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(paFlowInfo -> paFlowInfo.getSerialNo() + ";" + paFlowInfo.getRemark()))), ArrayList::new)
        );
    }

6、List根据两个属性转换为Map集合(作为key的属性不可重复)

public static Map transformMap(List list){
        return list.stream().collect(Collectors.toMap(paFlowInfo -> paFlowInfo.getSerialNo(), paFlowInfo -> paFlowInfo.getRemark()));
    }

7、从 List 中取出某个属性的组成 list 集合

public static List assemblyNewList(Listlist){
        return list.stream().map(PaFlowInfo::getSerialNo).collect(Collectors.toList());
    }

8、从 List 中取出某个属性的组成 list 集合 并去重

public static List assemblyNewListRemoveRep(Listlist){
        return list.stream().map(PaFlowInfo::getSerialNo).distinct().collect(Collectors.toList());
    }

9、删除map中value 为null的键值

public static void removeNull(Map map){
        map.entrySet().removeIf(entry -> entry.getValue() == null);
    }

 

你可能感兴趣的:(优雅代码,java)