th0sf4n
th0sf4n

Reputation: 35

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?

Upvotes: 2

Views: 183

Answers (5)

dani-vta
dani-vta

Reputation: 7180

You could iteratively count the occurrences of your characters and store them in a Map.

Map<Character, Long> mapRes = new HashMap<>();
for (Character c : list) {
    mapRes.put(c, mapRes1.getOrDefault(c, 0L) + 1);
}

Alternatively, you could employ java streams by using the aggregate operation groupingBy() with the downstream terminal operation counting().

Map<Character, Long> mapRes = list.stream()
    .collect(Collectors.groupingBy(c -> c, Collectors.counting()));

Here is also a sample test main at OneCompiler.

Upvotes: 0

Viktor Mellgren
Viktor Mellgren

Reputation: 4506

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);
  }

Upvotes: 0

Trishant Pahwa
Trishant Pahwa

Reputation: 2972

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.
    }
}

Upvotes: 0

Ashish Patil
Ashish Patil

Reputation: 4624

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);
...

Upvotes: 1

yaken
yaken

Reputation: 642

You've got the first part of the algorithm, the data processing:

  1. Process the data, from a text file to an ArrayList of characters, car.
  2. 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;
}

Upvotes: 0

Related Questions