更新列表中与之匹配的项目。

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

Update a list if there is any matching item

问题

如何使用流(streams)重写下面的代码?topics 是一个 ArrayList<Topic>

public void updateTopic(Topic topic) {
    topics.stream()
          .filter(t -> t.getId().equals(topic.getId()))
          .findFirst()
          .ifPresent(t -> topics.set(topics.indexOf(t), topic));
}
英文:

How can I write below code in streams? topics is an ArrayList&lt;Topic&gt;.

public void updateTopic(Topic topic) {
	for (int i = 0; i &lt; topics.size(); i++) {
		Topic t = topics.get(i);
		if (t.getId().equals(topic.getId())) {
			topics.set(i, topic);
			return;
		}
	}
}

答案1

得分: 1

你可以通过以下方式导入 IntStream

import java.util.stream.IntStream;
public void updateTopic(Topic topic) {
    IntStream.range(0, topics.size())
            .filter(i -> topics.get(i).getId().equals(topic.getId()))
            .findFirst()
            .ifPresent(i -> topics.set(i, topic));
}
英文:

You can use Intstream by importing it as follows

import java.util.stream.IntStream; 
public void updateTopic(Topic topic) {
    IntStream.range(0, topics.size())
            .filter(i -&gt; topics.get(i).getId().equals(topic.getId()))
            .findFirst()
            .ifPresent(i -&gt; topics.set(i, topic));
}

答案2

得分: 1

使用 Stream::map 如何?除非 ID 相等,否则映射到相同对象 - 然后映射到新对象。可以简单地使用三元运算符实现。

public void updateTopic(Topic topic) {
    topics = topics.stream()
        .map(t -> t.getId().equals(topic.getId()) ? topic : t)
        .collect(Collectors.toList());
}
英文:

How about using Stream::map? Map to the same object unless the ID are equal - then map to the new one. This can be achieved simply using the ternary operator.

public void updateTopic(Topic topic) {
    topics = topics.stream()
        .map(t -&gt; t.getId().equals(topic.getId()) ? topic : t)
        .collect(Collectors.toList());
}

huangapple
  • 本文由 发表于 2020年7月27日 15:18:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/63110444.html
匿名

发表评论

匿名网友

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

确定