我有一个包含重复字符串值的 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/