2016-11-26 60 views
8

我有一个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 
+2

为什么你存储在数组列表中的数据?这首先是要开始的。 –

+0

@ThomasJunk。我想要重复值的列表。无论如何? – user2196474

回答

9

好像你有正确的想法。你只需要使用一个Map,实际上算上遇到的字符串,而不是只提的是,他们遇到了:

Map<String, Integer> counter = new HashMap<>(); 
List<String> duplicateList = new ArrayList<>(); 

for (String item : list) { 

    // If String is not in set, add it to the list and the set, and 
    // note this is the first time it's encountered 
    if (!counter.containsKey(item)) { 
     duplicateList.add(item); 
     counter.put(item, 1); 
    } else { 
     Integer count = counter.get(item); 
     duplicateList.add(item + count); 
     item.put(item, count + 1); 
    } 
} 
7

假设你使用的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提议埃利奥特·弗里施保留价值的排序。从艾略特·弗里施的一个

稍微不同的方法:

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] 
4

您可以使用一个LinkedHashSet,您可以使用Arrays.asList(T...)来初始化你List 。首先,检查该集合是否包含list中的元素。如果是这样,重复值,直到找到一个尚未出现的值。喜欢的东西,

List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c", "d", 
     "b", "c", "a", "a", "a")); 
Set<String> mySet = new LinkedHashSet<>(); 
for (String str : list) { 
    if (mySet.contains(str)) { 
     int i = 1; 
     while (mySet.contains(str + i)) { 
      i++; 
     } 
     str = str + i; 
    } 
    mySet.add(str); 
} 
System.out.println(mySet); 

其输出(如需要)

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

@NicolasFilotto那个'List'是不可变的。不确定在OP的情况下是否重要。 –

相关问题