Reputation: 748
I have this loop:
List<Integer> numbers = new ArrayList<Integer>();
for(int x=0; x<citiesNames.size();x++){
List<Cities> numeroCiudades = citiesRepository.findByCity(citiesNames.get(x));
numbers.add(numeroCiudades.size());
//System.out.println(numeroCiudades.size());
}
where citiesNames is a List of String which contains 16584 elements and findByCity a method where I pass a String and it search in the database the correponding entries. What I want to do is to search the correponding entries of each city, check the number of entries, and add the number of entries to a Integer List. But this loop is too slow, is taking a very long time to show te result. How can I optimize this?
Upvotes: 0
Views: 702
Reputation: 688
I don't clearly get why you have to "pack" all cities in a List when you could create a function in citiesRepository that returns an int with the number of entries that particular city has. (That would increase performance a lot. Thus, the program would be able to just return a simple int instead of a whole class instantiation) (Supposing you have access to citiesRepository).
In addition, it could make sense to set assign list capacity in advance. On large list resizing can provoke significant performance drops (read more about how ArrayList works here)
Upvotes: 1
Reputation: 186
To optimize this loop, you will have to modify findByCity so that it could maybe process all of it at once. If you can't modify findByCity, you can always use parallelism with Streams:
int numbers[] = citiesNames.parallelStream()
.mapToInt(c -> citiesRepository.findByCity(c).size())
.toArray();
Upvotes: 0
Reputation: 5142
You could use a parallel stream, assuming citiesName
is a normal Java collections type:
citiesName.parallelStream()
.map(citiesRepository::findByCity)
.collect(Collectors.toList())
Just beware the pitfalls of the parallel stream and how it uses the shared ForkJoinPool
.
Upvotes: 0