[英]Move an element in the list to the first position using Stream
I have written this piece of code and I would like to convert it to stream
and while keeping the same behavior.我已经编写了这段代码,我想将其转换为
stream
并保持相同的行为。
List<String> str1 = new ArrayList<String>();
str1.add("A");
str1.add("B");
str1.add("C");
str1.add("D");
int index = str1.indexOf("C");
if ((str1.contains("C")) && (index != 0)) {
str1.remove("C");
str1.add(0, "C");
}
You could simplify:你可以简化:
int index = str1.indexOf("C");
if ((str1.contains("C")) && (index != 0)) {
str1.remove("C");
str1.add(0, "C");
}
as作为
if (str1.remove("C")) {
str1.add(0, "C");
}
(Check the javadoc for remove(Object)
. It removes the first instance of the object that it finds, and returns true
if an object was removed. There is no need to find and test the object's index.) (检查 javadoc 的
remove(Object)
。它会删除它找到的 object 的第一个实例,如果 object 被删除,则返回true
。无需查找和测试对象的索引。)
At this point, you should probably stop.在这一点上,你可能应该停下来。
A small gotcha is that if "C"
is the first element, you are removing it and adding it again... unnecessarily.一个小问题是,如果
"C"
是第一个元素,您将删除它并再次添加它......不必要的。 You could deal with this as follows:您可以按如下方式处理:
int index = str1.index("C"); if (index > 1) { str1.add(0, str1.remove(index)); }
You could optimize further to avoid the double copying of a remove and an add.您可以进一步优化以避免重复复制删除和添加。 For example (thanks to @Holger):
例如(感谢@Holger):
Collections.rotate(str1.subList(0, str1.indexOf("C") + 1), 1);
(But if you say that is simple, a regular Java programmer will probably throw something at you. It requires careful reading of the javadocs to understand that this is actually efficient.) (但如果你说这很简单,普通的 Java 程序员可能会向你扔东西。需要仔细阅读 javadocs 才能了解这实际上是有效的。)
You could rewrite this as 2 stream operations but there is no point doing it.您可以将其重写为 2 个 stream 操作,但这样做没有意义。 Both operations (remove first and insert into stream) are inefficient and tricky to implement.
这两种操作(首先删除并插入到流中)效率低下且难以实现。 Tricky to implement means hard to read.
难以实施意味着难以阅读。 Since the main point of streams is to express complex transformations in a way that is easier to read than conventional loops...
由于流的主要目的是以比传统循环更容易阅读的方式表达复杂的转换......
Note that the above solutions are for the problem as stated .请注意,上述解决方案是针对上述问题的。 However if object identity for the elements actually matters, the only one of the solutions above that actually moves an object to the start of the list is the solution that uses
rotate
.但是,如果元素的 object 身份确实很重要,则上述唯一将 object移动到列表开头的解决方案是使用
rotate
的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.