减少列表中的重复元素

时间:2018-10-13 00:00:16

标签: java

要压缩成没有重复元素的新列表,可能有空元素。我需要帮助。

我遇到此错误“ Tester Error(个人交付4):使用[1]调用时,该方法返回[]而不是[1]”。

domainname.com/somefolder/page.html

// -------------助手--------------------------------- -------------------------------

domainname.com/morefolder/anotherfolder/onemorefolder/somefolder/page.html

2 个答案:

答案 0 :(得分:1)

不清楚,如果要删除所有重复项或仅删除空值。这些可以消除骗子。

List<Comparable> l = ...; // The source list
List<Comparable> nl = new ArrayList<>(); // New list without dupes
Collections.sort(l);
Comparable last = UUIDs.randomUUID().toString(); // This one will never be in our source list
for (Comparable c: l) {
  if (!Objects.equal(c, last)) { // Or some other null-safe equals function
    nl.add(c);
  }
  last = c;
}

运行时间O(nlogn)。当然,列表中的元素需要实现明智的equals()hashCode()

Set<?> set = new HashSet<String>(); // Track "seen"
List<?> l = ...; // Original list
List<?> nl = new ArrayList<>(); // New list without dupes
for (Object o: l) {
  if (!set.contains(o)) {
    nl.add(o);
  }
  set.add(o);
}

运行时间为O(n),因为哈希集是恒定的查找时间。或更简单:

Set<?> set = new HashSet<String>(); // Will be collection without dupes
List<?> l = ...; // Original list
for (Object o: l) {
  set.add(o); // Rely on set semantics to remove dupes
}
List<?> nl = new ArrayList<>(set);

当然,列表中的对象必须实现明智的equals()hashCode()

答案 1 :(得分:0)

使用Java 8,您可以使用Stream different解决此问题。

示例代码如下。希望对您有帮助。

// input data
List<String> a = new ArrayList<>();
a.add("A");
a.add("A");
a.add("A");
a.add(null);
a.add(null);
Iterator source = a.iterator();
Iterable<String> iterable = () -> source;
// logic code
Iterator temp = StreamSupport
        .stream(iterable.spliterator(), false)
        .distinct()
        .collect(Collectors.toList()).iterator();
Iterable result = () -> temp;

// verify result
StreamSupport
        .stream(result.spliterator(), false)
        .forEach(System.out::println)

;

相关问题