/**
* 去除List中重复数据
* @author wjcom
* @Date 2010-12-22
* @version [版本号]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class test
{
/**
* @param args
*/
public static void main(String[] args)
{
Long[] initData = {1l, 10l,15l,1l,15l};
//方法一
List<Object> list1 = deleteRepeatIds1(initData);
for (int i = 0; i < list1.size(); i++)
{
System.out.println(list1.get(i));
}
System.out.println("==================");
//方法二
List list2 = deleteRepeatIds2(initData);
for (int j=0;j<list2.size();j++)
{
System.out.println(list2.get(j));
}
System.out.println("==================");
//方法三:最简洁的方法
List list3 = deleteRepeatIds3(initData);
for (int k=0;k<list3.size();k++)
{
System.out.println(list3.get(k));
}
}
/**
* 方法一
* @param ids
* @return
*/
private static List<Object> deleteRepeatIds1(Long[] ids)
{
List<Long> list = new ArrayList<Long>();
for (int j = 0; j < ids.length; j++)
{
list.add(ids[j]);
}
Set<Object> set = new HashSet<Object>();
List<Object> newList = new ArrayList<Object>();
for (Iterator iter = list.iterator(); iter.hasNext();)
{
Object element = iter.next();
if (set.add(element))
newList.add(element);
}
list.clear();
return newList;
}
/**
* 方法二
* @param ids
* @return
*/
private static List deleteRepeatIds2(Long[] ids)
{
List<Long> list = new ArrayList<Long>();
for (int j = 0; j < ids.length; j++)
{
boolean bl1 = true;
boolean bl2 = false;
if (list.size()>0)
{
for (int i = 0;i<list.size();i++)
{
if (list.get(i).equals(ids[j]))
{
bl2 = true;
}
}
bl1 = false;
}
if (bl1 || (!bl1 && !bl2))
{
list.add(ids[j]);
}
}
return list;
}
/**
* 方法三
* 最简洁的方法
* @param ids
* @return
*/
private static List deleteRepeatIds3(Long[] ids)
{
List<Long> list = new ArrayList<Long>();
for (int j = 0; j < ids.length; j++)
{
if (!list.contains(ids[j]))
{
list.add(ids[j]);
}
}
return list;
}
}
去除List中重复数据
最新推荐文章于 2024-05-01 05:48:27 发布