Home > Software design >  How to add up all the values in an ArrayList<String> or convert to ArrayList<Integer>
How to add up all the values in an ArrayList<String> or convert to ArrayList<Integer>

Time:04-17

I'm trying to add up all the values inside of an ArrayList but nothing allows me to get the sum. I have to find the average of the numbers pulled from a text file.

public static void main(String[] args) throws IOException {
    File file = new File("C:\\Users\\[REDACTED]\\Desktop\\mbox.txt");
    Scanner inputFile = new Scanner(file);
    ArrayList<Integer> ConfidenceLevels = new ArrayList<>();
    String [] DSPAM;
    String line;
    
    while(inputFile.hasNext())
    {
        line = inputFile.nextLine();
        if(line.startsWith("X-DSPAM-Confidence:"))
        {
            DSPAM = line.split(" 0");
            int x = Integer.parseInt(DSPAM[1].trim());
            ConfidenceLevels.add(x);
        }
    }
    System.out.println(ConfidenceLevels);
    System.out.println(ConfidenceLevels.size());
}

CodePudding user response:

You can try use IntSummaryStatistics and you can get min/max/average/sum of this list.

    IntSummaryStatistics intSummaryStatistics = ConfidenceLevels.stream().mapToInt(Integer::intValue).summaryStatistics();
    System.out.println(intSummaryStatistics.getAverage());
    System.out.println(intSummaryStatistics.getMin());
    System.out.println(intSummaryStatistics.getMax());
    System.out.println(intSummaryStatistics.getSum());

CodePudding user response:

You are just adding elements to the list. If you want the sum of them, you can create an Integer variable and add it.

public static void main(String[] args) throws IOException {
    File file = new File("C:\\Users\\[REDACTED]\\Desktop\\mbox.txt");
    Scanner inputFile = new Scanner(file);
    Integer confidenceLevelsSum = 0;
    String [] DSPAM;
    String line;
    
    while(inputFile.hasNext())
    {
        line = inputFile.nextLine();
        if(line.startsWith("X-DSPAM-Confidence:"))
        {
            DSPAM = line.split(" 0");

            // Check if it's null before trying to convert it.
            if (DSPAM[1] == null) {
                continue;
            }

            int x = Integer.parseInt(DSPAM[1].trim());
            confidenceLevelsSum  = x;
        }
    }
    System.out.println(confidenceLevelsSum);
}
  • Related