经测试比较高效的List去重算法
今天要写一个List的去重操作,看到网上很多都是利用set去重,结合实际情况,没法使用,原因如下
List里面是一个对象,只有某个属性是重复的,set没办法实现去重。
作为程序发烧友,跟同事们进行了一场比赛,看谁写的算法效率最高。于是,经过三个人的不断调试,总结出来了高效的去重算法,
废话不说,看代码。
private ArrayList<Model> distinctList(ArrayList<Model> list){ ArrayList<Model> newList = new ArrayList<Model>(); Set<String> set = new HashSet<String>(); for (Model item:list){ <span style="color:#ff0000;">if (set.add(item.str)){ newList.add(item); }</span> } return newList; }Model代码
class Model { public int id; public String str; }主要的部分就是利用set的特性去比较。
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
- 上一篇: 轻松搞定权限设计1-页面按钮控制(精确到某个用户和某个按钮)
- 下一篇: 源码编译安装php5.6