Created
November 23, 2023 08:51
-
-
Save jjarzynski/14b2a32d8d84909525a8779eb5c29c0f to your computer and use it in GitHub Desktop.
Interview 00
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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