Set<String> set = new HashSet<>(list);
List<String> uniqueList = new ArrayList<>(set);
Stream<String> stream = list.stream();
distinct()
方法去除重复元素。List<String> uniqueList = stream.distinct().collect(Collectors.toList());
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
@Setter
和@Getter
注解。import lombok.Setter;
import lombok.Getter;
@Setter
@Getter
public class UniqueData {
private String value;
}
List<UniqueData> list = new ArrayList<>();
list.add(new UniqueData("A"));
list.add(new UniqueData("B"));
list.add(new UniqueData("A"));
removeIf()
方法去除重复数据。list.removeIf(uniqueData -> list.stream().filter(ud -> ud.getValue().equals(uniqueData.getValue())).count() > 1);
<dependency>
<groupId>com.github.kokorin.unique</groupId>
<artifactId>unique-hash-set</artifactId>
<version>1.1.0</version>
</dependency>
UniqueHashSet
去除重复数据。import com.github.kokorin.unique.UniqueHashSet;
Set<String> uniqueSet = new UniqueHashSet<>(list);
以上四种方法都可以用于实现集合去重。方法一是基于HashSet,方法二是基于Java 8的Stream API,方法三是基于Lombok库,方法四是基于第三方库UniqueHashSet