集合(元素是字符串和对象)去重

集合去重是我们常见的逻辑,分为两种:集合元素是String字符串和集合元素是对象

集合元素是String字符串的去重:

首先写一个工具类ArrayUtil:

public class ArrayUtil {
 /**
 * 集合去重
 *
 * @param list
 * @return
 */
public static ArrayList<String> pastLeep(List<String> list) {
   ArrayList<String> listNew = new ArrayList<>();
   Set set = new HashSet();
   for (String str : list) {
      if (set.add(str)) {
         listNew.add(str);
      }
   }
   return listNew;
   }
}

使用场景:

//时长费区间
ArrayList<String> timeFee = new ArrayList<>();
ArrayList<String> milesFee = new ArrayList<>();
//里程区间
List<GeneralChargeDetail> milestonesFees = generalChargeStandardEntity.getMilestonesFees();
if(milestonesFees!=null &&  milestonesFees.size()>1){
    for (GeneralChargeDetail milestonesFee : milestonesFees) {
        timeFee.add(milestonesFee.getStartTime()+"-"+milestonesFee.getEndTime());
    }
    ArrayList<String> pastLeepTimeFee = ArrayUtil.pastLeep(timeFee);

集合元素是对象的两种方式去重:

方式一:

List<SpecialLine> specialLines = companyFacade.getAllSpecialLines();
StringBuilder sb = new StringBuilder();
for (SpecialLine specialLine : specialLines) {
    if(specialLine.getStartId().equals(startAdCode)){
        //去重判断
        if(-1 != sb.indexOf(specialLine.getEndId())) {
                continue;
        }

方式二:

lambda 表达式去重,需要在jdk1.8版本以上

//对象去重 去重相同的市
List<StartCityDTO> startCityDTOS = new LinkedList<>();
for (StartCityDTO startCityDTO1 : startCityDTOS1) {
    if(null !=startCityDTO1.getStartAdCode()||"".equals(startCityDTO1.getStartAdCode()) ){
        boolean b = startCityDTOS.stream().anyMatch(u -> u.getStartAdCode().equals(startCityDTO1.getStartAdCode()));
        if (!b) {
            startCityDTOS.add(startCityDTO1);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值