'How do I count every unique item in an Arraylist?
I need to count every unique character in an Arraylist. I already seperated everys single character.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class Aschenputtel {
public static void main(String args[]) {
ArrayList <String> txtLowCase = new ArrayList <String> ();
ArrayList <Character> car = new ArrayList <Character> ();
File datei = new File ("C:/Users/Thomas/Downloads/Aschenputtel.txt");
Scanner scan = null;
try {
scan = new Scanner (datei);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
while (scan.hasNext()) {
String temp = scan.next().replace("„", "„").replace("“", "“").toLowerCase();
txtLowCase.add(temp);
for(int i = 0; i < temp.length(); i++) {
car.add(temp.charAt(i));
}
}
System.out.println(car);
}
}
That is my current code. car currently gives every single character but the result should be something like: a = 16, b = 7, c = 24,.... Is there a good way to do that?
Solution 1:[1]
Once you have your character you can do something like in your for loop :
...
Map<Character, Integer> map2=new HashMap<Character, Integer>();
for (int i = 0; i < temp.length(); i++) {
map2.put(temp.charAt(i), map2.getOrDefault(temp.charAt(i), 0)+1);
}
System.out.println(map2);
...
Solution 2:[2]
You've got the first part of the algorithm, the data processing:
- Process the data, from a text file to an ArrayList of characters,
car. - Count the characters in the list.
You want to associate each character to a count. A HashMap would be great for that.
Here's a method for the second part, with some explanations:
/*
This will return something that looks like:
{ a: 16, b: 7, c: 24, ... }
*/
HashMap<Character, Int> getCharacterCount(ArrayList<Character> charList) {
// for each character we associate an int, its count.
HashMap<Character, Int> counter = new Hashmap<>();
for (Character car: charList) {
// if the map doesn't contain our character, we've never seen it before.
int currentCount = counter.containsKey(car) ? counter.get(car) : 0;
// increment this character's current count
counter.put(car, currentCount + 1);
}
return counter;
}
Solution 3:[3]
If you need to count the number of characters within your car list, you could use a collection stream and the aggregate operation groupingby in conjunction with the downstream counting.
This operation will yield a Map whose keys are the list's characters and their corresponding values their occurrences within the list.
Sample Code
List<Character> list = new ArrayList<>(List.of('a', 'a', 'a', 'b', 'c', 'b', 'b', 'b', 'a', 'c'));
Map<Character, Long> mapRes = list.stream().collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println(mapRes);
Your Code
public class Aschenputtel {
public static void main(String args[]) {
ArrayList<String> txtLowCase = new ArrayList<String>();
ArrayList<Character> car = new ArrayList<Character>();
File datei = new File("C:/Users/Thomas/Downloads/Aschenputtel.txt");
Scanner scan = null;
try {
scan = new Scanner(datei);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
while (scan.hasNext()) {
String temp = scan.next().replace("„", "„").replace("“", "“").toLowerCase();
txtLowCase.add(temp);
for (int i = 0; i < temp.length(); i++) {
car.add(temp.charAt(i));
}
}
Map<Character, Long> mapRes = car.stream().collect(Collectors.groupingBy(c -> c, Collectors.counting()));
System.out.println(mapRes);
}
}
Solution 4:[4]
Here is the most simplistic approach, pass on your array list to a HashSet when initializing it.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class Aschenputtel {
public static void main(String args[]) {
ArrayList <String> txtLowCase = new ArrayList <String> ();
ArrayList <Character> car = new ArrayList <Character> ();
File datei = new File ("C:/Users/Thomas/Downloads/Aschenputtel.txt");
Scanner scan = null;
try {
scan = new Scanner (datei);
} catch (FileNotFoundException e) {
System.out.println("File not found.");
}
while (scan.hasNext()) {
String temp = scan.next().replace("„", "„").replace("“", "“").toLowerCase();
txtLowCase.add(temp);
for(int i = 0; i < temp.length(); i++) {
car.add(temp.charAt(i));
}
}
HashSet<String> hset = new HashSet<String>(ArrList); // Only adds an element if it doesn't exists prior.
System.out.println("ArrayList Unique Values is : " + hset); // All the unique values.
System.out.println("ArrayList Total Coutn Of Unique Values is : " + hset.size()); // Count of all unique items.
}
}
Solution 5:[5]
If you want to have more control/customizability you could also do something like this:
private static void calcCount(List<Character> chars) {
chars.sort(Comparator.naturalOrder());
Character prevChar = null;
int currentCount = 0;
for (Character aChar : chars) {
if (aChar != prevChar) {
if (prevChar != null) {
System.out.print(currentCount + " ");
currentCount = 0;
}
System.out.print(aChar + ":");
prevChar = aChar;
}
currentCount++;
}
System.out.print(currentCount);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ashish Patil |
| Solution 2 | yaken |
| Solution 3 | Dan |
| Solution 4 | Trishant Pahwa |
| Solution 5 | Viktor Mellgren |
