ran*_*ibt 3 java collections arraylist set
对于给定的列表,假设[ "a", "a", "b", "c", "c" ]我需要[ "b" ](仅非重复元素)作为输出.请注意,这与使用Set作业界面不同...
我在Java中编写了以下代码来执行此操作:
void unique(List<String> list) {
    Collections.sort(list);
    List<String> dup = new ArrayList<>();
    int i = 0, j = 0;
    for (String e : list) {
        i = list.indexOf(e);
        j = list.lastIndexOf(e);
        if (i != j && !dup.contains(e)) {
            dup.add(e);
        }
    }
    list.removeAll(dup);
}
它有效...但是对于大小为85320的列表,几分钟后结束!
你最好的表现是设置:
    String[] xs = { "a", "a", "b", "c", "c" };
    Set<String> singles = new TreeSet<>();
    Set<String> multiples = new TreeSet<>();
    for (String x : xs) {
        if(!multiples.contains(x)){
            if(singles.contains(x)){
                singles.remove(x);
                multiples.add(x);
            }else{
                singles.add(x);
            }
        }
    }
它是单个传递,插入,删除和包含是log(n).
使用Java 8流:
return list.stream()
    .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
    .entrySet()
    .stream()
    .filter(e -> e.getValue() == 1)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());