user1953346
user1953346

Reputation: 49

Java: convert List<List<String>> into List<List<Double>>

I have a List-List from a Filereader (String), how can I convert it into a List-List (Double): I have to return a List of the first Values of the line-Array. Thanks.

 private List<List<String>> stoxxFileReader(String file, int column) throws IOException {

        List<List<String>> allLines = new ArrayList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(file))) {

          br.readLine();
          String line = null;

          while ((line = br.readLine()) != null) {
                  String[] values = line.split(",");  

            allLines.add(Arrays.asList(values));     

        }   
    }
        return allLines;

Upvotes: 2

Views: 2521

Answers (3)

Edwin
Edwin

Reputation: 33

I'm not sure what you are trying to get as output exactly, but it's not that complicated in any case. Assuming you have something like this:

[["1", "2"],
 ["3", "4"]]

If you want to get all the first elements as Double [1, 3] (Assuming the first element is always present):

        List<Double> firstAsDouble = allLines.stream()
            .map(line -> line.get(0))
            .map(Double::parseDouble)
            .collect(Collectors.toList());

If instead you just want to convert all String values to Double and keep the structure the same:

        List<List<Double>> matrix = allLines.stream()
            .map(line -> line.stream().map(Double::parseDouble).collect(Collectors.toList()))
            .collect(Collectors.toList());

Or if you'd like to output a single array with all values ([1, 2, 3, 4]), you can flatMap it:

        List<Double> flatArray = allLines.stream()
            .flatMap(line -> line.stream().map(Double::parseDouble))
            .collect(Collectors.toList());

Upvotes: 0

Lal Mohandas
Lal Mohandas

Reputation: 116

The java.util.stream.Collectors have a handy method for this. Please refer to the below code snippet. You can replace with your logic

    Map<String, Integer> map = list.stream().collect(
            Collectors.toMap(kv -> kv.getKey(), kv -> kv.getValue())); 

Upvotes: 0

sai
sai

Reputation: 75

you can use below method to convert all the list of String to Double

public static <T, U> List<U> convertStringListTodoubleList(List<T> listOfString, Function<T, U> function) 
   { 
       return listOfString.stream() 
           .map(function) 
           .collect(Collectors.toList()); 
   }

Calling Method

List<Double> listOfDouble = convertStringListTodoubleList(listOfString,Double::parseDouble);

Upvotes: 2

Related Questions