简体   繁体   中英

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.

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.)

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. 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):

     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.)

  • You could rewrite this as 2 stream operations but there is no point doing it. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM