This question already has an answer here:
- Take n random elements from a List<E>? 9 answers
I set up a web application using Java-SpringBoot and MySQL on backend side. I have a RestFUL API that return different info usin AJAX calls from front side. I have an endpoint that returns a a full list of exercices. Now I'm creating another enpoint that should return only 5 random exercices from all the exercices, and I can't figure out how to do that using Streams
The code is all made using MVC and ORM to get the database, with the controller
This is the method to get the full list of exercices:
public List getExercices(String discipline, List<String> group, List<Integer> level){
if(discipline.equals("calisthenics")){
return exercices_calisthenicsRepository.findAll()
.stream()
.filter(el->group.contains(el.getGroup()) && level.contains(el.getLevel()))
.collect(Collectors.toList());
}
}
And now I want to filter this full list, and return only 5 random exercices.
The way I made it work, is by saving the info in a variable, and then taking 5 random exercices from the list. Something like this:
//Create two empty list
List exercices = new ArrayList<>();
List routine = new ArrayList<>();
//Save all the exercices in one of this lists
exercices = (exercices_calisthenicsRepository.findAll()
.stream()
.filter(el.getGroup()) && level.contains(el.getLevel()))
.collect(Collectors.toList()));
//Create 5 random numbers
Random rand = new Random();
int random1 = rand.nextInt(exercices.size());
int random2 = rand.nextInt(exercices.size());
int random3 = rand.nextInt(exercices.size());
int random4 = rand.nextInt(exercices.size());
int random5 = rand.nextInt(exercices.size());
//Add this elements from first List, to the final list
routine.add(exercices.get(random1));
routine.add(exercices.get(random2));
routine.add(exercices.get(random3));
routine.add(exercices.get(random4));
routine.add(exercices.get(random5));
//Return final list with 5 exercices
return routine;
I would say, there should be a much simpler way to do it just by using Streams, and maybe filtering right there instead of saving all the info in a List, and then generating a second list from it.
Does anybody know if it's possible to do it just by using Streams?
Thank you very much!
Aucun commentaire:
Enregistrer un commentaire