英文:
Best way to fill a map using java steams
问题
第一个样式:
list.stream().map(e -> new AbstractMap.SimpleEntry<>(e.getId(), e.getPrice())).forEach(priceByID.entrySet()::add);
第二个样式:
Map<String, Double> map = list.stream().collect(Collectors.toMap(e -> e.getId(), e -> e.getPrice()));
priceByID.putAll(map);
英文:
We have a map that we are filling in multiple calls from a list passed as a param:
Map<String, Double> priceByID
Which style is considered a cleaner code to fill our map? Why?
list.stream().map(e -> new AbstractMap.SimpleEntry<>(e.getId(), e.getPrice())).forEach(priceByID.entrySet()::add);
OR
Map<String, Double> map = list.stream().collect(Collectors.toMap(e -> e.getId(), e -> e.getPrice()));
priceByID.putAll(map);
答案1
得分: 1
list.forEach(e -> priceByID.put(e.getId(), e.getPrice()));
或者甚至可以这样写:
for (?? entry : list) {
priceByID.put(entry.getId(), entry.getPrice());
}
英文:
list.stream().map(e -> new AbstractMap.SimpleEntry<>(e.getId(), e.getPrice())).forEach(priceByID.entrySet()::add);
> You are creating a stream of map entries, and the go over it and insert it. there's no real reason to do it, you creating tones of redundant objects
Map<String, Double> map = list.stream().collect(Collectors.toMap(e -> e.getId(), e -> e.getPrice()));
priceByID.putAll(map);
> again, creating redundant map that will be removed afterwards, and also go over the items twice - once on the stream, and again on the putAll
you can use:
list.forEach(e -> priceByID.put(e.getId(), e.getPrice()))
or even:
for (?? entry : list) {
priceByID.put(entry.getId(), entry.getPrice()));
}
it will do the job just the same.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论