用Java流填充映射的最佳方法

huangapple go评论63阅读模式
英文:

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&lt;String, Double&gt; priceByID 

Which style is considered a cleaner code to fill our map? Why?

list.stream().map(e -&gt; new AbstractMap.SimpleEntry&lt;&gt;(e.getId(), e.getPrice())).forEach(priceByID.entrySet()::add);

OR

 Map&lt;String, Double&gt; map = list.stream().collect(Collectors.toMap(e -&gt; e.getId(), e -&gt; 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 -&gt; new AbstractMap.SimpleEntry&lt;&gt;(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&lt;String, Double&gt; map = list.stream().collect(Collectors.toMap(e -&gt; e.getId(), e -&gt; 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 -&gt; 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.

huangapple
  • 本文由 发表于 2020年10月18日 14:18:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64410317.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定