[英]Java8 Lambda compare two List and trasform to Map
Suppose I have two class:假设我有两个 class:
class Key {
private Integer id;
private String key;
}
class Value {
private Integer id;
private Integer key_id;
private String value;
}
Now I fill the first list as follows:现在我填写第一个列表如下:
List<Key> keys = new ArrayLisy<>();
keys.add(new Key(1, "Name"));
keys.add(new Key(2, "Surname"));
keys.add(new Key(3, "Address"));
And the second one:第二个:
List<Value> values = new ArrayLisy<>();
values.add(new Value(1, 1, "Mark"));
values.add(new Value(2, 3, "Fifth Avenue"));
values.add(new Value(3, 2, "Fischer"));
Can you please tell me how can I rewrite the follow code:你能告诉我如何重写以下代码:
for (Key k : keys) {
for (Value v : values) {
if (k.getId().equals(v.getKey_Id())) {
map.put(k.getKey(), v.getValue());
break;
}
}
}
Using Lambdas?使用 Lambda?
Thank you!谢谢!
‐------UPDATE------- - - - -更新 - - - -
Yes sure it works, I forget "using Lambdas" on the first post (now I added).是的,它确实有效,我忘记了第一篇文章中的“使用 Lambdas”(现在我添加了)。 I would like to rewrite the two nested for
cicle with Lamdas.我想用 Lamdas 重写两个嵌套for
cicle。
Here is how you would do it using streams.以下是使用流的方法。
Map<String, String> results = keys.stream()
.flatMap(k -> IntStream.range(0, values.size())
.filter(i -> k.getId() == values.get(i).getKey_id())
.mapToObj(i -> new AbstractMap.SimpleEntry<>(
k.getKey(), values.get(i).getValue())))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue));
results.entrySet().forEach(System.out::println);
prints印刷
Address=Fifth Avenue
Surname=Fischer
Name=Mark
Imo, your way is much clearer and easier to understand. Imo,你的方式更清晰,更容易理解。 Streams/w lambdas or method references are not always the best approach. Streams/w lambdas 或方法引用并不总是最好的方法。
A hybrid approach might also be considered.也可以考虑采用混合方法。
(isPresent)
add to map.找到值(isPresent)
添加到 map。Map<String,String> map = new HashMap<>();
for (Key k : keys) {
Optional<Value> opt = values.stream()
.filter(v -> k.getId() == v.getKey_id())
.findFirst();
if (opt.isPresent()) {
map.put(k.getKey(), opt.get().getValue());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.