身处一个电商公司,分类肯定是能接触到的。所以问题也就来了,前端页面传来了一大堆分类id,我们怎么去判断其中的重复内容。
package cn.neepu.category;import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;import java.util.List;@Data
@Accessors(chain = true)
public class CheckModel {private Integer firstLevelId;private Integer secondLevelId;private Integer thirdLevelId;public CheckModel(){}public CheckModel(List ids){switch(ids.size()){case 3:thirdLevelId=ids.get(2);case 2:secondLevelId=ids.get(1);case 1:firstLevelId=ids.get(0);default:break;}}@Setter(AccessLevel.NONE)@Getter(AccessLevel.NONE)private Integer level;public String getLevelString() {if (level == null) {fillLevel();}String str = "";char split = '#';switch (level) {case 3:str = "" + thirdLevelId + split + str;case 2:str = "" + secondLevelId + split + str;case 1:str = "" + firstLevelId + split + str;default:break;}return str;}private void fillLevel() {if (thirdLevelId != null) {level = 3;} else if (secondLevelId != null) {level = 2;} else if (firstLevelId != null) {level = 1;} else {level = 0;}}
}
package cn.neepu.category;import org.apache.commons.collections4.CollectionUtils;import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;public class CheckUtils {public static Set repeat(List list){if(CollectionUtils.isEmpty(list)){return Collections.emptySet();}HashSet set = new HashSet<>();List levelStringList = list.stream().map(CheckModel::getLevelString).sorted().collect(Collectors.toList());for (int i = 1; i < levelStringList.size(); i++) {String preLevelString = levelStringList.get(i - 1);String thisLevelString = levelStringList.get(i);if(thisLevelString.startsWith(preLevelString)){set.add(preLevelString);}}return set;}
}
里面用了一些lombok注解,都是奇技淫巧。。。
还有switch 的用法,在阿里这可是不建议(不允许)的,也不知道为啥要有这规定。。。代码本来就是灵活的,非要整的一板一眼。
还有一些魔法值,这个确实可以优化。
对于调用者来说:
class Main {public static void main(String[] args) {CheckModel checkModel = new CheckModel().setFirstLevelId(12);CheckModel checkModel3 = new CheckModel().setFirstLevelId(12);List list = new ArrayList<>();list.add(checkModel);list.add(checkModel3);System.out.println(list);Set repeat = CheckUtils.repeat(list);System.out.println(repeat);List repeatModel = list.stream().filter(item -> repeat.stream().anyMatch(repeatString -> item.getLevelString().startsWith(repeatString))).collect(Collectors.toList());System.out.println(repeatModel);}
}
另外 CheckModel
这个东西只是用来校验的,其他方法入参肯定不是这样,这时候为了优雅一点,可以这么用
package cn.neepu.category;import lombok.Data;import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;@Data
public class CategoryDTO {private List> cascadeId;public List getCheckModelList() {return Optional.ofNullable(cascadeId).map(Collection::stream).orElseGet(Stream::empty).map(CheckModel::new).collect(Collectors.toList());}}
lambda是个好东西。应该还有优化的空间,还请大家指教。
下一篇:轴承轮廓测量解决方案