Skip to content
Advertisement

How to sum elements of List

I want to sum the possibilities (of some characters) in the context of Shannon-Fano Algorithm.

Example input/output

Given poss as a List of Strings filled with possibilities. For example the possibilities are as follows:

poss = {"0.33333334", "0.2", "0.13333334", "0.13333334", "0.13333334", "0.06666667"}

and the sum must be 1 (after adding all the possibilities).

What I already tried

Following code is what I tried. But the problem is that the code does not recognize the possibilities as integers and the code goes to the catch:

ArrayList<String> poss = new ArrayList <String>();

private static void ShannonFano(ArrayList<String> poss, Map<Character, Float> m) {
    System.out.println("Possibility for each character in descending order " + poss);
    int sumOfp = 0;
    int sum = 0;
    for (String element: poss) {
        try {
            int num = Integer.parseInt(element);
            sum += num;
        } catch(NumberFormatException nfe) {
            System.out.println("Element " + element + " in the array is not an integer");
        }

    }
}

I tried it also with just a for loop, but then I got a sum of 0 and I don’t know why.

My question

How can I treat the possibilities as integers in order to calculate the sum of them?

Advertisement

Answer

You can write a method the handle parsing exception getDouble() and use it in a for loop or in a stream:

public static void main(String[] args) throws InterruptedException {
     double result = poss.stream()
            .map(YourClass::getDouble)
            .reduce(Double::sum)
            .get();
}

private static Double getDouble(final String s) {
    try {
        return Double.parseDouble(s);
    }catch (Exception e){
        return 0.0;
    }
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement