I have a method in which I am trying to return a Map<String, Long> with a stream of strings as its parameter.
The string is a line from a csv file with comma separated lines and values.
What I want to return is a map of ONLY the Num 1-4 columns and the counts of their occurrences of the number 1.
The example str that I defined below is expected to return a Map<String, Long> of {Num1 = 1, Num2 = 0, Num3 = 2, Num4 = 1}.
My main issue is that I do not understand how to collect the ones from each of these columns as I assume that they are multiple objects and a terminal collect operation can seemingly only cover one column.
public static Map<String, Long> returnNumCountsOf1(Stream<String> str) {
// returns a map with the name of the Num columns (key) and their counts (value) of the number 1
// ex.) str = "WORD1 WORD2 WORD3 WORD4 Num1 Num2 Num3 Num4 WN1 WN2 WN3",
"a, b, c, d, 1, 2, 3, 4, one, two, three",
"e, f, g, h, 4, 3, 1, 2, one, two, seven",
"i, j, k, l, 2, 4, 3, 1, one, nine, eleven",
"m, n, o, p, 3, 4, 1, 2, one, five, three";
Map<String, Long> pow = new HashMap<>();
pow = str
.map(x -> x.split(","))
.skip(1) //ignores the header
.filter(x -> x.length == 11) // splits into indexes
.collect(Collectors.groupingBy(x -> x[5]?, Collectors.counting()));
return pow;
//Expected return value should be {Num1=1, Num2=0, Num3=2, Num4=1}.
stringand the function namecountAllInstancesOfOnedon't seem like good names. The current state of your question is very confusing.