Skip to content

Instantly share code, notes, and snippets.

@jjarzynski
Created November 23, 2023 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjarzynski/14b2a32d8d84909525a8779eb5c29c0f to your computer and use it in GitHub Desktop.
Save jjarzynski/14b2a32d8d84909525a8779eb5c29c0f to your computer and use it in GitHub Desktop.
Interview 00
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
interface ItemsRepository {
List<Integer> findByType(String type);
// Dummy implementation, but please assume this is a proper DB repository:
ItemsRepository INSTANCE = type -> IntStream.rangeClosed(1, (int) (Math.random() * 999 + 2))
.boxed()
.collect(Collectors.toList());
}
interface PricesRepository {
Integer findPriceById(Integer id);
Map<Integer, Integer> findPricesByIds(List<Integer> ids);
// Dummy implementation, but please assume this is a proper DB repository:
PricesRepository INSTANCE = id -> 3 * id;
}
class Main {
public static void main(String[] args) {
final int allBraceletsPrice = totalPriceOfAllItemsForType("bracelet");
System.out.println("bracelets: " + allBraceletsPrice);
final int allNecklacesPrice = totalPriceOfAllItemsForType("necklace");
System.out.println("necklaces: " + allNecklacesPrice);
}
// Focus on the performance of the following method:
static int totalPriceOfAllItemsForType(final String type) {
return ItemsRepository.INSTANCE.findByType(type)
.stream()
.map(PricesRepository.INSTANCE::findPriceById)
.mapToInt(Integer::intValue)
.sum();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment