Removing duplicate elements in an ArrayList and adding the total number of occurrences in parentheses after the first element

Beginner is here. I have a String ArrayList that essentially looks like this (but with varying values ​​depending on user input) when printing:

[22, 37, 77, 77, 98, 101, 104, 107, 107, 107, 150]

I want to remove duplicate elements and add the total number of occurrences in parentheses after the first element, so it will look like this:

[22, 37, 77 (2), 98, 101, 104, 107 (3), 150]

I figured out how to remove duplicate items, but I can't figure out everything else.

Here is my code so far (ArrayList called duplication):

int q, z; for(q = 0; q < duplicates.size() - 1; q++) { for(z = q + 1; z < duplicates.size() - 1; z++) { if(duplicates.get(q).equals(duplicates.get(z))) { duplicates.remove(q); } } } System.out.println(duplicates); 

Resulting result:

[22, 37, 77, 98, 101, 104, 107, 150]

Does anyone have any suggestions on how I can get these parentheses with the number of occurrences there? I struggled to come up with a way to remove duplicates for each value, but all I managed to calculate was the total number of deleted periods, which is not particularly useful.

ArrayList was originally an Integer ArrayList, but I changed it to a String ArrayList, so I could add non-numbers to elements.

+4
source share
8 answers

I would recommend using Map . You can use this to associate keys with useful values. In this case, the key will be an element of your array that will be processed, and the value will be the number of occurrences of each element in the array. Your pseudocode will look like this:

 initialize a map of appropriate size and type iterate the array to be processed. for each element in array: set key:= current element in array set value := value from map corresponding to key if value is null, initialize value to 1 store value for key in map 

Then at the end you will iterate over the keys of the card and print out both the key and its corresponding value.

+2
source

ArrayList was originally an Integer ArrayList, but I changed it to a String ArrayList, so I could add non-numbers to elements.

This is mistake. Do not mix how you want to store your data in your code and how you want to display it to the user. If you save your values ​​as a List of String , you make things harder for yourself. Save the values ​​in the form that is easiest to encode, and only hidden for the rows when you want to display them.

So what you want is a list of unique numbers and a count for each of them. A Map would be ideal as it displays the key - in your reason, an integer - value - count.

So, you need to fixate on your numbers, and then count them in Map . In the code below, I assume List is a List<Integer> .

 Map<Integer,Integer> counts = new HashMap<Integer,Integer>(); for (int number : list) { int count = counts.containsKey(number) ? counts.get(number) : 0; count += 1; counts.put(number,count); } 

Then you can create your output by going through Map.keySet() or Map.entrySet() ,

+1
source

First of all, I suggest saving the list as a list of integers. Do not use System.out.println(duplicates) , but run the loop yourself. In any case, it is really easy.


Event Counting:

I suggest you support Map<Integer, Integer> , which maps numbers to the number of occurrences. This can be initialized in the first pass as follows:

  • For each item, I am in the list (n)
    • If I am not in the map (n)
      • add mapping i β†’ 0 ( map.put(i, 0) )
    • Increase the value for key i ( map.put(i, map.get(i) + 1) )


Print a list with the number of entries:

You print the list as follows:

  • Create a HashSet<Integer> printed for already printed numbers
  • For each item I'm listed
    • If I printed , do, continue: ( if (printed.contains(i)) continue; )
    • Print i
    • If the display has a value> 1 for i, type the number in brackets
    • Add me to print. ( printed.add(i) )

Once you finish practicing loops, you can remove duplicates by simply doing

 list = new ArrayList<Integer>(new LinkedHashSet<Integer>(list)); 
0
source

declare ArrayList<Integer> for counting:

 ArrayList<Integer> counts = new ArrayList<Integer>(); 

and then when you delete the duplicate dial

  duplicates.remove(q); counts.set(q, counts.get(q) + 1); 
0
source

LinkedHashMap is good enough for you. A hash table and a linked list of map interface implementations with predictable iteration order. Therefore, I recommend using LinkedHashMap as follows:

  public static LinkedHashMap<String,Integer> removeDuplicate(List<String> list) { LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>(); for(String str:list) { Integer count = map.get(str); if(count == null) { map.put(str, 1); }else{ map.put(str, ++count); } } return map; } public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("123"); list.add("45"); list.add("678"); list.add("123"); System.out.println(removeDuplicate(list)); } 
0
source

With a little help (IMHO very useful) Google Library Guava you can write this:

 List<String> duplicate = ImmutableList.of("22", "37", "77", "77", "98", "101", "104", "107", "107", "107", "150"); System.out.println(duplicate); Multiset<String> withoutDuplicate = LinkedHashMultiset.create(); withoutDuplicate.addAll(duplicate); System.out.println(withoutDuplicate); 

It will create

 [22, 37, 77, 77, 98, 101, 104, 107, 107, 107, 150] [22, 37, 77 x 2, 98, 101, 104, 107 x 3, 150] 

This is not exactly your format, but for this it is two-line.

0
source
 List<Integer> completeList = new ArrayList<Integer>(); completeList.add(22); completeList.add(22); completeList.add(37); completeList.add(77); completeList.add(77); completeList.add(98); completeList.add(101); completeList.add(107); completeList.add(107); completeList.add(107); completeList.add(150); System.out.println(completeList); // Using a sortedSet to remove the duplicates SortedSet<Integer> nonDupSet = new TreeSet<Integer>(completeList); System.out.println(nonDupSet); List<String> datawithParan = new ArrayList<String>(); //Looping through the completeList with the nonDup List and counting the dups. // and then populating a List with the required Format for (Integer nonDup: nonDupSet) { int count = 0; for (Integer complete: completeList) { if(nonDup == complete) { count++; } } datawithParan.add(nonDup +"(" + count + ")"); } System.out.println(datawithParan); 
0
source

Here is the complete code for you:

 public static void main(String[] args) { /* Make list */ List<String> input = new ArrayList<String>(); input.add("12"); input.add("11"); input.add("11"); input.add("12"); input.add("12"); input.add("15"); input.add("12"); input.add("17"); input.add("18"); input.add("11"); /* * count duplicates */ Map<String, Integer> map = new LinkedHashMap<String, Integer>(); for (String str : input) { if (map.containsKey(str)) { Integer prevCount = map.get(str); map.put(str, ++prevCount); } else { map.put(str, 0); } } /* * make string to display */ StringBuffer sb = new StringBuffer(); for (Map.Entry<String, Integer> entry : map.entrySet()) { String key = entry.getKey(); Integer count = entry.getValue(); if (count == 0) { sb.append(key + ", "); } else sb.append(key + "(" + count + "), "); } String tmp = sb.toString(); String output = tmp.substring(0, tmp.length() - 2); //remove last ", " System.out.println("[" + output + "]"); } 
-1
source

Source: https://habr.com/ru/post/1402854/


All Articles