0

I am trying to convert my string to int so that I can sum the values.

  1. The original value is "GBP 1.00 GBP 500.00";
  2. I need to split it and remove GBP so that the only remaining are integer values (1.00, 500.00) and store it in List.
  3. Now, I want to convert it to List so I can add the values: 1.00 and 500.00 equals 501.00.
import java.util.List;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.function.Function;

public class Main { 
  public static void main(String[] args) { 
    String num = "GBP 1.00 GBP 500.00";
        List<String> al = new ArrayList<String>(Arrays.asList(num.split(" ")));
        al.removeIf(n -> (n.charAt(0) == 'G'));
        
        
        System.out.println("Num: "+num);
        System.out.println("Al: "+al);
        System.out.println(al.get(0));
        System.out.println(al.get(1));
        System.out.println(al.get(1)+al.get(0));
        

        //---Convert List<String> to List<Int>- to add the values------------------//
       System.out.println("Convert List<String> to List<Int>");
       //Code here
        
  } 
}

//Result

Num: GBP 1.00 GBP 500.00
Al: [1.00, 500.00]
1.00
500.00
500.001.00
  • Why do you convert to `int` when the numbers definitely look like `double`? – Nowhere Man Mar 18 '21 at 11:51
  • `List values = list.stream().map(text -> text.split(" ")[1]).map(Integer::valueOf).toList()`. (or `...collect(Collectors.toList())` if you are not on Java 16 yet). You can also just `...mapToInt(Integer::parseInt).sum()` if u only need the sum. – Zabuzard Mar 18 '21 at 11:51
  • Well, you could use `Double.parseDouble()`. With a stream it could be something like : `al.filter(s -> s.matches("[0-9]+\\.[0-9]+")).mapToDouble(Double::parseDouble).sum()` (since Alex is right and your values look like double values) – Thomas Mar 18 '21 at 11:52
  • Thanks @Thomas it is now working. Here is the code: – user15256728 Mar 18 '21 at 12:28
  • String num = "GBP 1.00 GBP 500.00"; List al = new ArrayList(Arrays.asList(num.split(" "))); al.removeIf(n -> (n.charAt(0) == 'G')); Double test = al.stream().filter(s -> s.matches("[0-9]+\\.[0-9]+")).mapToDouble(Double::parseDouble).sum(); //al.filter(s -> s.matches("[0-9]+\\.[0-9]+")).mapToDouble(Double::parseDouble).sum(); System.out.println("Num: "+test); – user15256728 Mar 18 '21 at 12:29
  • @user15256728 note that the `filter(...)` should already remove any non-numeric strings from the stream so the `removeIf()` shouldn't be necessary. – Thomas Mar 19 '21 at 07:09

0 Answers0