list去重
定义一个对象。
package com.example.demo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.Data;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* @Auther : YOUGROOT
* @Date : 2018/7/17 下午2:05
*/
public class ListDemo {
@Data
public static class Person{
private String id;
private String name;
private Integer age;
private Integer score;
public Person(String id, String name, Integer age, Integer score) {
this.id = id;
this.name = name;
this.age = age;
this.score = score;
}
public Person() {
}
@Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
1、创建对象,放入list集合中。
public static void main(String[] args) {
Person p1 = new Person("1", "T", 23, 87);
Person p2 = new Person("2", "Y", 24, 98);
Person p3 = new Person("3", "T", 23, 87);
Person p4 = new Person("4", "Y", 24, 98);
Person p5 = new Person("5", "U", 23, 87);
Person p6 = new Person("6", "I", 24, 98);
Person p7 = new Person("7", "U", 23, 87);
Person p8 = new Person("8", "I", 24, 98);
List<Person> list1 = Lists.newArrayList();
list1.add(p1);
list1.add(p2);
list1.add(p5);
list1.add(p6);
List<Person> list2 = Lists.newArrayList();
list2.add(p3);
list2.add(p4);
list2.add(p7);
list2.add(p8);
List<List<Person>> list = Lists.newArrayList();
list.add(list1);
list.add(list2);
List<Person> tempList = Lists.newArrayList();
2、首先想到的是先把多层list转成一层list。
List<Person> finalPersonList = Lists.newArrayList();
list.forEach(e -> {
e.forEach(f -> {
tempList.add(f);
});
});
3、第一种方法是利用map的key不可重复,实现去重。
Map<String, Person> map = Maps.newHashMap();
tempList.forEach(e -> {
map.put(e.getName(), e);
});
Map<String, Person> newMap = Maps.newTreeMap();
map.forEach((k, v) -> {
newMap.put(v.getId(), v);
});
newMap.forEach((k, v) -> {
finalPersonList.add(v);
});
4、 第二种方法是利用Collections.frequency()方法,但是只能去重相同的对象。
//方法二:去重操作(Collections.frequency方法)只能去重相同的对象
tempList.forEach(e -> {
//调用Collections.frequency方法
if (Collections.frequency(finalPersonList, e) < 1){
finalPersonList.add(e)
}
})
5、这里另外加了一个排序的方法Collections.sort(),按照对象中的一个属性进行排序,升降序可以根据return -1和return 1来控制。
Collections.sort(finalPersonList, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if (Integer.parseInt(o1.getId()) > Integer.parseInt(o2.getId())){
return -1;
}
if (Integer.parseInt(o1.getId()) < Integer.parseInt(o2.getId())){
return 1;
}
return 0;
}
});
finalPersonList.forEach(e -> {
System.out.println(e);
});
}
}
总结
- Collections.frequency()方法是容易被遗忘的,这是一种去重的方法
- 排序,目前比较容易掌握的是放进TreeMap里面,升序排序
- 利用 Collections.sort()方法排序,可以控制升序或者降序