How to use forEach() method in Java 8 loop n time but my list size is always random like n-1, n-2, etc.... If list size is less then n number then rest value would be zero/empty of each object value.
Below example I have Data3 object which have ID, year, listOfCompanies and value as per below code in the end I have list of Data3 object which I want to loop using for each java8 but I want to loop 8 times for list of companies if no value then put Empty value for each object.
I try using IntStream.range function but its not working for me.
@lombok.Data
@AllArgsConstructor
static class Data3{
int id;
int year;
List<String> listOfCompanies;
double value;
}
List<String> list1 = new ArrayList<>();
list1.add("TCS"); list1.add("Cognizant");list1.add("Wipro");list1.add("Zensar");
list1.add("IBM");list1.add("Amdocs");
List<String> list2 = new ArrayList<>();
list2.add("TCS");list2.add("Cognizant");list2.add("Wipro");
List<String> list3 = new ArrayList<>();
list3.add("TCS");list3.add("Cognizant");list3.add("Wipro");list3.add("Zensar");
list3.add("IBM");
List<String> list4 = new ArrayList<>();
list4.add("TCS");list4.add("Cognizant");
Data3 d1 = new Data3(1, 1990, list1, 10);
Data3 d2 = new Data3(2, 1991, list2, 20);
Data3 d3 = new Data3(3, 1992, list3, 30);
Data3 d4 = new Data3(4, 1993, list4, 40);
List<Data3> listOfDataValues = new ArrayList<>();
listOfDataValues.add(d1);
listOfDataValues.add(d2);
listOfDataValues.add(d3);
listOfDataValues.add(d4);
listOfDataValues.stream().map(value -> new Data3(value.getId(), value.getYear(), IntStream.range(1, 8).mapToObj(index -> value.getListOfCompanies().get(index).isEmpty() ? "" : value.getListOfCompanies().get(index)), value.getValue()));
Expected OP: (result required to loop 8 times list of companies if no
value then put Empty value )
[Test.Data3(id=1, year=1990, listOfCompanies=[TCS, Cognizant, Wipro, Zensar, IBM, Amdocs,"",""], value=10.0),
Test.Data3(id=2, year=1991, listOfCompanies=[TCS, Cognizant, Wipro,"","","","",""], value=20.0),
Test.Data3(id=3, year=1992, listOfCompanies=[TCS, Cognizant, Wipro, Zensar, IBM,"","",""], value=30.0),`
Test.Data3(id=4, year=1993, listOfCompanies=[TCS, Cognizant,"","","","","",""], value=40.0)]
>Solution :
listOfDataValues.stream().forEach(value -> {
return IntStream.range(1, 8).mapToObj(new Data3(value.getId(), value.getYear(), value.getListOfCompanies(), value.getValue()));
});
The code snippet is wrong for:
1.in forEach you don’t need to return anything
2.mapToObj needs IntFunction, so you need to take an Integer as input
Actually you need to complement "" according to the size of listOfCompanies, so getting the quantity to be complemented is the key:
listOfDataValues.stream().forEach(value -> {
int size = value.getListOfCompanies().size();
IntStream.range(0, 8 - size).forEach(index->value.getListOfCompanies().add(""));
});