I am new to Java 8 streams, I am unable to get the correct output from the nested loop operational sum.
In the nested loop, I am calling a method which is returning an integer; by this doing finally summing up the resultant total
This is what I tried:
import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;
public class NestedLoop {
public void callTask(int i, int j) {
System.out.println("i:"+i+"j:"+j);
}
public int getCount(Count count, String j) {
if(count.getCount() >= 123 && count.getCount() <= 125) {
System.out.println("###");
return 1;
}
else {
return 0;
}
}
public static void main(String[] args) {
List<Count> list2 = new ArrayList<>();
List<String> list1 = new ArrayList<>();
Count count = new Count(121);
Count count1 = new Count(122);
Count count2 = new Count(123);
Count count3 = new Count(124);
Count count4 = new Count(125);
list2.add(count4);
list2.add(count2);
list2.add(count3);
list2.add(count1);
list2.add(count);
NestedLoop loop = new NestedLoop();
list1.add("list2 - Op1");
list1.add("list2 - Op2");
list1.add("list2 - Op2");
list1.add("list2 - Op2");
int _count = 0;
IntStream res = list2.parallelStream().flatMapToInt(x -> IntStream.of(list1.stream().mapToInt(y-> loop.getCount(x,y)).sum()));
System.out.println(res.sum());
}
}
Count class
class Count {
private int count;
public Count(int count) {
super();
this.count = count;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
By this, I am getting 12 instead of 2.
Help, me where the code is faulty.
See Question&Answers more detail:os