Skip to content
Snippets Groups Projects
Commit 75494077 authored by Holzheu Hannah's avatar Holzheu Hannah
Browse files

Merge branch 'Handling_pages_randomPlantsEndpoint' into 'main'

added page Handling for getRandomPlants Endpoint #19

See merge request !22
parents ecde77e3 ab380105
No related branches found
No related tags found
Loading
...@@ -13,10 +13,7 @@ import org.springframework.data.domain.Pageable; ...@@ -13,10 +13,7 @@ import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification; import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.*;
import java.util.Collection;
import java.util.List;
import java.util.Random;
@Service @Service
@RequiredArgsConstructor @RequiredArgsConstructor
...@@ -37,23 +34,16 @@ public class PlantsService { ...@@ -37,23 +34,16 @@ public class PlantsService {
} }
public Collection<Plant> getRandomPlants(int numberOfPlants) { public Collection<Plant> getRandomPlants(int numberOfPlants) {
List<Plant> allPlants = plantRepository.findAll(); numberOfPlants= Math.min(MAX_PAGE_SIZE, numberOfPlants);
long plantCount= plantRepository.count();
int lastPage= (int)(plantCount/numberOfPlants)-1;
int randomPage= (int) (Math.random()*lastPage);
if (allPlants.size() <= numberOfPlants) { CustomPageDto<Plant> randomPlantPage= getPlants(randomPage, numberOfPlants);
return allPlants; List<Plant> allPlantsOfPage = new ArrayList<>(randomPlantPage.content());
} else { Collections.shuffle(allPlantsOfPage);
List<Plant> randomPlants = new ArrayList<>();
Random random = new Random();
while (randomPlants.size() < numberOfPlants) { return allPlantsOfPage;
Plant randomPlant = allPlants.get(random.nextInt(allPlants.size()));
if (!randomPlants.contains(randomPlant)) {
randomPlants.add(randomPlant);
}
}
return randomPlants;
}
} }
public Collection<Plant> getPlantsSearchedFor(SearchRequest searchRequest) { public Collection<Plant> getPlantsSearchedFor(SearchRequest searchRequest) {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment