简体   繁体   中英

How to transform List<XObject> to List<XObjectWrapper>?

public class XObject {
...
}

public class XObjectWrapper
{
  private final XObject xo;

  public XObjectWrapper(XObject xo) {
    this.xo = xo;
  }
//delegated methods
...
}

I have List<XObject> , I want to get List<XObjectWrapper> .

Obviously, I can do something like this:

List<XObjectWrapper> wrappedList = new ArrayList<XObjectWrapper> ();
for(XObject xo : xoList) 
{
  wrappedList.add(new XObjectWrapper(xo));
}

Can I use some new java8 feature, and do it with a single line?

This will do:

List<XObjectWrapper> wrappedList = 
   xoList.stream().map(XObjectWrapper::new).collect(toList());

(Assuming import static java.util.stream.Collectors.toList; )

Update

For completeness, and due to possible errors in your code, here is a self-contained example:

import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.List;

static class XObjectWrapper {XObjectWrapper(Object o) {}}
static class XObject {}

public class Test {
  public static void main(String[] args) {
    List<Object> xoList = new ArrayList<>();
    List<XObjectWrapper> wrappedList =
        xoList.stream().map(XObjectWrapper::new).collect(toList());
    System.out.println(wrappedList);
  }
}

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