英文:
One liner for comparing by property and returning a stream?
问题
可以像下面这样在一行中对流进行排序并返回吗?
//@Getter...
public List<Actor> actors;
public Stream<Actor> actors() {
//这两行是否可以以某种方式合并?
return actors.stream().sorted(Comparator.comparing(Actor::getName));
}
**注意:**在发布此问题后,我收集到这可能会导致设计不理想且可能容易出错,因为它会在方法外部改变状态。感谢@knittl指出这一点。
英文:
Is it possible to sort and return a stream in one line as in the following?
//@Getter...
public List<Actor> actors;
public Stream<Actor> actors() {
//can these two lines be combined somehow?
actors.sort(Comparator.comparing(Actor::getName));
return actors.stream();
}
Note: After posting this question, I gather this would lead to a design that is not ideal and perhaps error-prone, as it would mutate state outside of the method. Thanks to @knittl for pointing this out.
答案1
得分: 0
Streams有一个sorted方法
actors.stream().sorted(Comparator.comparing(Actor::getName))
注意:这不会对List
英文:
Streams has a sorted method
actors.stream().sorted(Comparator.comparing(Actor::getName))
Note: This will not sort the List<Actors>. And will only sort the returned stream.
答案2
得分: 0
你可以这样做:
return actors.stream().sorted(Comparator.comparing(Actor::getName));
List的sort方法会返回void,因此无法连接。
问候
英文:
you can do it like this:
return actors.stream().sorted(Comparator.comparing(Actor::getName));
The sort Method of a List will return void, so there is no chance to concat.
Greetings
答案3
得分: 0
以下是翻译好的部分:
如果你真的,真的必须:
public Stream<Actor> actors() {
return (actors = actors.stream()
.sorted(Comparator.comparing(Actor::getName))
.toList()).stream();
}
因为可能性存在,并不意味着你应该这样做。
但确实,knittl是对的。你不应该用这个getter方法改变actors
。如果我使用这个方法,然后突然actors
被排序了,我会非常惊讶。
有一些更好的替代方案可以改进你当前的设计:
-
对结果流进行排序,但不改变
actors
:return actors.stream() .sorted(Comparator.comparing(Actor::getName));
-
在初始化时对
actors
进行排序,例如:List<Actor> actors; YourConstructor(List<Actor> actors) { this.actors = actors.stream() .sorted(Comparator.comparing(Actor::getName)) .toList(); // 或者根据需要选择List的实现方式 }
英文:
If you really, really must:
public Stream<Actor> actors() {
return (actors = actors.stream()
.sorted(Comparator.comparing(Actor::getName))
.toList()).stream();
}
Because it is possible, doesn't mean you should do this.
But indeed, knittl is right. You shouldn't mutate actors
with this getter method. I'd be really surprised if I were to use this method and suddenly actors
was sorted.
There are some options which are better alternatives to your current design:
-
Sort the resulting stream, but don't mutate
actors
:return actors.stream() .sorted(Comparator.comparing(Actor::getName));
-
Sort
actors
on initialization, for example:List<Actor> actors; YourConstructor(List<Actor> actors) { this.actors = actors.stream() .sorted(Comparator.comparing(Actor::getName)) .toList(); // Or whatever implementation of List is desired }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论