简体   繁体   English

Java:按顺序包含唯一元素的列表

[英]Java : list that contains unique elements in order

Is there a list type in java that stores objects in ascending order and not adds if this object is previously added. java中是否有列表类型以升序存储对象,如果之前添加了此对象,则不添加。 I know java maps can do that but I wonder if there is a list type that does what I want.我知道 java 地图可以做到这一点,但我想知道是否有一种列表类型可以满足我的需求。 Otherwise I have to override contains, equalsTo and add methods,right?否则我必须覆盖 contains、equalsTo 和 add 方法,对吗?

So you need a list containing only unique elements?所以你需要一个只包含唯一元素的列表? Two options:两种选择:

  • java.util.LinkedHashSet - preserves the order of insertion, has the set semantics java.util.LinkedHashSet - 保留插入顺序,具有集合语义
  • from commons-collections SetUniqueList - allows list operations like get(..) and set(..)来自 commons-collections SetUniqueList - 允许列表操作,如get(..)set(..)
  • from commons-collections ListOrderedSet来自 commons-collections ListOrderedSet

Depends on what order do you mean.取决于你的意思是什么顺序。

TreeSet will do the trick. TreeSet 可以解决问题。 Example :例子 :

SortedSet<Integer> myOrderedUniqueList = new TreeSet<Integer>()

I think you're after a SortedSet (this is an interface which extends Set).我认为您在追求 SortedSet (这是一个扩展 Set 的接口)。 Set is like a List but it contains only one of each value. Set 就像一个列表,但它只包含每个值中的一个。

TreeSet is a commonly-used implementation of SortedSet TreeSet 是 SortedSet 的常用实现

http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html

SortedSet is a subinterface of Set, which guarantees that the elements in the set are sorted. SortedSet 是 Set 的一个子接口,它保证集合中的元素是有序的。

SortedSet<Integer> orderedSet = new TreeSet<Integer>();

Use them when you have to stores non-duplicate elements in increasing order of the element values当您必须按元素值的递增顺序存储非重复元素时使用它们

TreeSet might be exactly what you need. TreeSet可能正是您所需要的。

It stores the elements in a sorted tree.它将元素存储在排序树中。 So you can iterate over them in sorted order.因此,您可以按排序顺序迭代它们。 It's not a list, but it performs better with respect to add and contains.它不是一个列表,但它在添加和包含方面表现更好。

使用 java.util.LinkedHashSet 与覆盖 hashCode() 和 equals(Object obj) 使用唯一属性

public static <T> List<T> getUniqueListOrdered(List<T> values) {
    Set<T> uniqueValues = new HashSet<>();
    return values.stream().filter(value -> uniqueValues.add(value)).collect(Collectors.toList());
}


@Test
public void createUnique() {
    List<String> unique = ListUtils.getUniqueListOrdered(Arrays.asList("A", "A", "A", "B", "B"));
    Assert.assertEquals(unique, Arrays.asList("A", "B"));
}

它不是一个列表,但您可以查看 Sethttp://download.oracle.com/javase/6/docs/api/java/util/Set.html 的实现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM