2016-11-26 44 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的情況下是否重要。 –

相關問題