-3

I am using SuperCSV library to read a csv file with the method below. However, the method returns a Collection<Object> and I need a Collection<Double>. I am already using the Optional(new ParseDouble()) processors which converts every cell to a Double.

The question is how do you convert it/ cast it/ or is there another way?

Also, if possible I need to avoid any expensive operations since this method is called frequently.

    private static Collection<Object> partialReadWithCsvMapReader(int row, String[] header, CellProcessor[] processors) throws Exception {

    ICsvMapReader mapReader = null;
    Map<String, Object> rowMap = null;

    try {
        mapReader = new CsvMapReader(new FileReader(CSV_FILENAME), CsvPreference.STANDARD_PREFERENCE);
        mapReader.getHeader(true);

        while( (rowMap = mapReader.read(header, processors)) != null ) {

            if(mapReader.getLineNumber() == row){
                break;
            }
        }
    }

    finally {
        if( mapReader != null ) {
            mapReader.close();
        }
    }
    return rowMap.values();
}

The question is in the context of the SuperCSV library. Since the individual values are already converted to Doubles by the processors - would it be possible to return a Collection<Double>instead of having to convert the collection once again.

Edv Beq
  • 910
  • 3
  • 18
  • 43

2 Answers2

3

Iterate over the collection and use parseDouble:

List<Double> list = new ArrayList<Double>();
for(Object obj : rowMap.values()) {
    list.add(Double.parseDouble(String.valueOf(obj)));
}
ThomasEdwin
  • 2,035
  • 1
  • 24
  • 36
2

A Java 8 solution involves using the java.util.stream package:

I would use Collection#stream to get a stream of the collecton, then useStream#mapToDouble to convert it in a one line statement:

return rowMap.values().stream().mapToDouble(obj -> {
    if (obj instanceof String)
        return Double.parseDouble(String.valueOf(obj));
    else if (obj instanceof Double)
        return (double) obj;
    return 0;
}).boxed().collect(Collectors.toList());
Cardinal System
  • 2,749
  • 3
  • 21
  • 42
  • 2
    With the caveat of if OP is using Java 8+, not everyone is yet – paisanco Dec 22 '17 at 02:44
  • 3
    @paisanco Not everyone is using Java 5 yet. – shmosel Dec 22 '17 at 02:48
  • 3
    @paisanco Java 7 has been out of public updates for 2.5 years by now. If the OP doesn't want to use at least the oldest supported version of Java, they should say so in the question. https://www.java.com/en/download/faq/java_7.xml – Erwin Bolwidt Dec 22 '17 at 03:06