繁体   English   中英

转换列表 <MyObject> 列表 <List<String> &gt;仅使用java8 lambdas

[英]Convert List<MyObject> to List<List<String>> using java8 lambdas only

我有List<User> ,其中User是一个具有变量id,name,date 。我只想创建一个List<List<String>> ,它只包含第一个List<List<String>>中的名称和日期。我的代码

import java.util.*;
import java.util.stream.*;
public class User
{
  int id;
  String name;
  Date date;

  public User(int id,String name,Date date){
    this.id=id;
    this.name=name;
    this.date=date;

  }

  public static void main(String[] args)
  {
    User one=new User(1,"a",new Date());
    User two=new User(2,"b",new Date());
    User three=new User(3,"c",new Date());

    List<User> userList=Arrays.asList(one,two,three);

    System.out.println(userList);

    List<List<String>> stringList = IntStream.range(0,userList.size())
                                             .maptoObj(i -> Array.asList(userList.get(i).name,userList.get(i).date))
                                             .collect(toList);
    System.out.print(stringList);

  }
}

我似乎无法弄清楚当我使用collect()时我怎么能实现它,它说无法在收集时找到符号。 有什么方法可以从List<User>获取包含名称和日期列表的List<List<String>>

我也试过了

List<List<String>> stringList = IntStream.range(0,userList.size())
                                         .map(i -> Arrays.asList(userList.get(i).name,userList.get(i).date.toString()))
                                         .collect(Collectors.toList());

但它给了我

 error: 
    no instance(s) of type variable(s) T exist so that List<T> conforms to int
  where T is a type-variable:
    T extends Object declared in method <T>asList(T...)incompatible types: bad return type in lambda expression
                                             .map(i -> Arrays.asList(userList.get(i).name,userList.get(i).date.toString()))
                                                                    ^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

谢谢

您不需要使用IntStream

List<List<String>> output = 
    userList.stream()
            .map (u -> Arrays.asList (u.name,u.date.toString()))
            .collect (Collectors.toList());

编辑:

如果您希望继续使用IntStream解决方案:

List<List<String>> stringList = 
    IntStream.range(0,userList.size())
             .mapToObj(i -> Arrays.asList(userList.get(i).name,userList.get(i).date.toString()))
             .collect(Collectors.toList());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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