java - 在列表中查找重复的字符串并使它们唯一

标签 java list duplicates unique

我有一个包含重复字符串值的 ArrayList,我想通过附加一个计数来使重复值唯一。

public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("d");
    list.add("b");
    list.add("c");
    list.add("a");
    list.add("a");
    list.add("a");

    HashSet<String> set = new HashSet<String>();
    List<String> duplicateList = new ArrayList<String>();

    for (String item : list) {
        // If String is not in set, add it to the list and the set.
        if (!set.contains(item)) {              
            set.add(item);
        } else {
            duplicateList.add(item);
        }
    }

    for (String element : duplicateList) {
        System.out.println(element);
    }
}

有什么方法可以使列表像这样:

a
b
c
d
b1
c1
a1
a2
a3

最佳答案

假设您使用 Java 8,如果您想获得 List 中每个值的重复项总数,您可以通过 Stream API 做到这一点按值分组,然后计算每个值的出现次数:

Map<String, Long> counter = list.stream()
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(counter);

输出:

{a=4, b=2, c=2, d=1}

如果您想通过在原始 String 末尾添加计数器来防止重复,您可以使用 LinkedHashSet 来保留值的顺序,如 Elliott Frisch 所建议的那样.

Elliott Frisch 的方法略有不同:

List<String> list = Arrays.asList("a", "b", "c", "d", "b", "c", "a", "a", "a");
Set<String> set = new LinkedHashSet<>();
for (String str : list) {
    String value = str;
    // Iterate as long as you can't add the value indicating that we have
    // already the value in the set
    for (int i = 1; !set.add(value); i++) {
        value = str + i;
    }
}
System.out.println(set);

输出:

[a, b, c, d, b1, c1, a1, a2, a3]

关于java - 在列表中查找重复的字符串并使它们唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40816421/

相关文章:

java - 在 Spring Boot 中加载外部 jar

r - 从 R 中的数据帧创建复杂的列表结构

java - XSD/Maven : Duplicate entry

python - 如何从列表中获取唯一值(删除重复项)?

java - 你能直接将 pdf 打印到斑马打印机吗

java - Maven 创建快速入门模板

java - 用于基于 Java 模板的字符串构造的工具

list - JPA OneToMany - 添加/删除对象后列表不会更新,但会保留在数据库中

python - 如何将列表中的元素合并在一起?

mysql - 删除具有两个重复字段但没有重复 ID 的 MySQL 行