【发布时间】:2015-10-22 08:16:21
【问题描述】:
我有List<User>,其中User 是一个具有变量id,name,date 的类。我只想用它创建一个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<List<String>> 包含来自List<User> 的姓名和日期列表
我也试过
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
谢谢
【问题讨论】:
-
是否要将
Date对象放入字符串列表中? -
你的错误在
collect(toList),toList不存在,是toList()。 -
@marstran 不,我想将其转换为字符串
标签: java list collections lambda java-8