the object of this specific function is to create a list of (competitor objects ) Using 2 lists containing time and names.
note that this is a trail to convert from object oriented to functional programing , so its actually a record rather than an object.
my initial trial using a sort of recursion
public static List<Competitors> makeObjects(int[] time, String[] name){
if (counter > name.length){
return racers;
}else{
Competitors racer= new Competitors(name[counter],backToTime(time[counter]));
racers.add(racer);
return makeObjects(++counter,racers,time,name);
}
and my try after discovering i can use streams
public static List<Competitors> makeObjects(int[] time, String[] name){
List<Competitors> racers = new ArrayList<Competitors>();
IntStream.range(0,time.length).mapToObj(i-> ).collect(new Competitors(name[i] ,backToTime(time[i])))
}
Your second approach, makeObjects()
, is the functional approach.
Where you go wrong is that you are creating the Competitor
objects in the wrong place; you map each i
to a new Competitor. Then in the collect()
call, you specify what type of collection. In your case, it would be Collectors.toList()
or Collectors.toSet()
. There is no need to create an ArrayList
; just assign the IntStream...
to List<Competitor> racers
.
Note that you should probably guard this method by first asserting that the arrays are the same length.
Also note that your class should be named Competitor
, not Competitors
; and makeObjects
would be more descriptive as createCompetitorsList
.