Pregunta

I have tried Scanner to read a text file into an arraylist. Let's assume that I have an arraylist like this

[A, MANBA]
[A, PGD]
[A, GUSB]
[A, GLB1]
[B, HS6ST1]
[B, NDST1]
[B, NDST4]
[C, NRP1]
[C, ZEB1]

How can I count the occurrence of the first value and print it out ? As this particular example, the output will be

A  4
B  3
C  2

Here is the code I have so far. Any suggestion would be grateful.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;

public class PI_list{
public static void main (String[] args) throws FileNotFoundException
{
    Scanner inputFile = new Scanner(new File("/home/tab.csv"));
    while(inputFile.hasNextLine()){
        String line = inputFile.nextLine();
        ArrayList<String> PPIData = new ArrayList<String>();
        Scanner scanner = new Scanner(line);
        scanner.useDelimiter("\t");
        while(scanner.hasNext()){
            PPIData.add(scanner.next());
        }
        scanner.close();

        System.out.println(PPIData);
    }

    inputFile.close();
    }
}
¿Fue útil?

Solución 2

Method with simple for

public String countOccurences(String letter,List<String> array){
  int counter = 0; 
  for(String s : array){
      if(s.equals(letter))
        counter++;
   }
  return letter + ": " + String.valueOf(counter);
}

public void getResult(List<String> array){
  Set<String> setOfLetters = new HashSet<String>();
  List<String> dataArray = new ArrayList<String>();
  for(String s: array){
     s.replace("[","");
     s.replace("]","");
     String tab[] = s.split(",");
     setOfLetters.add(tab[0]);
     dateArray.add(tab[0]);
 }
 for(String s: setOfLetters)
    countOccurences(s,dataArray);
}

so simply your code should look like that

public static void main (String[] args) throws FileNotFoundException
{
    Scanner inputFile = new Scanner(new File("/home/tab.csv"));
    while(inputFile.hasNextLine()){
        String line = inputFile.nextLine();
        ArrayList<String> PPIData = new ArrayList<String>();
        Scanner scanner = new Scanner(line);
        scanner.useDelimiter("\t");
        while(scanner.hasNext()){
            PPIData.add(scanner.next());
        }
        scanner.close();
        getResult(PPIData);
        System.out.println(PPIData);
    }

Of course with access to my above methods.

Merging it all your class should look like

public class PI_list {

    public static String countOccurences(String letter, List<String> array) {
        int counter = 0;
        for (String s : array) {
            if (s.equals(letter))
                counter++;
        }
        return letter + ": " + String.valueOf(counter);
    }

    public static void getResult(List<String> array) {
        Set<String> setOfLetters = new HashSet<String>();
        List<String> dataArray = new ArrayList<String>();
        for (String s : array) {
            s.replace("[", "");
            s.replace("]", "");
            String tab[] = s.split(",");
            setOfLetters.add(tab[0]);
            dataArray.add(tab[0]);
        }
        for (String s : setOfLetters)
            System.out.println(countOccurences(s, dataArray));
    }

    public static void main(String[] args) throws FileNotFoundException {
        Scanner inputFile = new Scanner(new File("/home/tab.csv"));
        while (inputFile.hasNextLine()) {
            String line = inputFile.nextLine();
            ArrayList<String> PPIData = new ArrayList<String>();
            Scanner scanner = new Scanner(line);
            scanner.useDelimiter("\t");
            while (scanner.hasNext()) {
                PPIData.add(scanner.next());
            }
            getResult(PPIData);
            System.out.println(PPIData);
        }
        inputFile.close();
    }

}

Otros consejos

Have a look at guavas MultiMap. That's exactly what you are looking for.

As per your code

while(inputFile.hasNextLine()){
        String line = inputFile.nextLine();
        ArrayList<String> PPIData = new ArrayList<String>();
        Scanner scanner = new Scanner(line);
        scanner.useDelimiter("\t");
        while(scanner.hasNext()){
            PPIData.add(scanner.next());
        }
        scanner.close();

        System.out.println(PPIData);
    }

    inputFile.close();
    }

The arraylist is locally scoped so you can't use it outside the while loop.

In case you want to use it later some point to count the occurances of letter, then declare it above the while loop.

Steps for solution:

  1. Iterate through the arrayList

  2. Get the first element which will contain [A, MANBA] as string

  3. Split the string based on comma, get the value A

  4. Now pass the value A to a function where you will check the occurrences of A in the ArrayList.

Mostly this will give you concurrency exception as you will be processing same arraylist.

Better solution:

Use guava-libraries Multimap which will be easier for your scenario

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top