集合相关

多线程列表删除的解决方案

第一种:Collections.synchronizedList
最常用的方法是通过 Collections 的 synchronizedList 方法将 ArrayList 转换成线程安全的容器后再使用。

1
List<Object> list =Collections.synchronizedList(new ArrayList<Object>);

第二种: CopyOnWriteArrayList
使用线程安全的 CopyOnWriteArrayList 代替线程不安全的 ArrayList

1
List<Object> list1 = new CopyOnWriteArrayList<Object>();

第三种:
按索引从大到小,这样remove方法的删除元素导致的后面的元素往前移动一位

1
2
3
4
5
6
for (int i = list.size()-1; i >=0; i--) {
System.out.println(i);
if(list.get(i).equals("C")){
list.remove(list.get(i));
}
}

将集合内匹配的数据移到首位

1
2
3
4
5
6
7
int matchIndex = -1;
for (City city : citys) {
if (TextUtils.equals(city.getRegionId(), locationCity.getRegionId())) {
matchIndex = citys.indexOf(city);
}
}
citys.add(0, citys.remove(matchIndex));

List去重

法1: 使用HashSet实现List去重(无序)

1
2
3
4
5
6
7
8
9
10
11
12
13
/**使用HashSet实现List去重(无序)
*
* @param list
*
*/
public static List removeDuplicationByHashSet(List<Integer> list) {
HashSet set = new HashSet(list);
//把List集合所有元素清空
list.clear();
//把HashSet对象添加至List集合
list.addAll(set);
return list;
}

法2: 使用TreeSet实现List去重(有序)

1
2
3
4
5
6
7
8
9
10
11
12
13
/**使用TreeSet实现List去重(有序)
*
* @param list
*
*/
public static List removeDuplicationByTreeSet(List<Integer> list) {
TreeSet set = new TreeSet(list);
//把List集合所有元素清空
list.clear();
//把HashSet对象添加至List集合
list.addAll(set);
return list;
}