1

This is my CSV, first line is header, Akt (pan), Mc1-1 and etc. is content. I need to create a function that extracts content of SearchTerm column and adds it to a List<String>.

I tried it with this piece of code but my next processing requires to have List<String> and not List<String[]>. Is there a way to do that or is there any way i can take parsed List<String[]> and make it into List<String> only containing all the search terms?

My CSV

public List<String> listAllSearchTerms() throws FileNotFoundException {
    CsvParserSettings settings = new CsvParserSettings();
    settings.selectIndexes(0);
    CsvParser parser = new CsvParser(settings);
    List<String[]> allRows = parser.parseAll(new FileReader("D:\\Projects\\cstocs-test-dev-bitbucket\\cstocs-test-core\\src\\main\\resources\\data\\searchterm.csv"));
    List<String> returnList = new ArrayList<>();
    allRows.remove(0);
    for (String[] strings : allRows) {
        returnList.addAll(Arrays.asList(strings));
    }
    return returnList;
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
Radovan Kočík
  • 61
  • 1
  • 2
  • 7
  • Please write what is the problem with the mentioned sample of code? It seems that the sample already does what you want to do. – Armine Sep 18 '19 at 09:12
  • Probably create a bean class for the `SearchTerms` and follow this question will get the clarity: https://stackoverflow.com/questions/22485041/how-to-easily-process-csv-file-to-listmyclass – Mohamed Saligh Sep 18 '19 at 09:15

2 Answers2

1

If you know which column SearchTerm is you can replace the for loop with

for (String[] strings : allRows) {
     returnList.add(strings[0]); //Assumes it's the first column
}
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
-1

is there any way i can take parsed List and make it into List only containing all the search terms?

    String[] strArr1 = {"a", "b", "c"};
    String[] strArr2 = {"d", "e", "f"};

    List<String[]> stringArrList = new ArrayList<>();
    stringArrList.add(strArr1);
    stringArrList.add(strArr2);

    List<String> collect = stringArrList.stream()
            .map(arr -> arr[0])
            .collect(Collectors.toList());

    System.out.println(collect);

output:

[a, d]
Jude Niroshan
  • 4,280
  • 8
  • 40
  • 62
  • I think just the first column "SearchTerm" was intended. Then instead of `flatMap` there should be `.map(arr -> arr[0])`. Though a Stream solution is perfect. – Joop Eggen Sep 18 '19 at 09:24