将List <myobject>转换为List <list <string>&gt;仅使用java8 lambdas

时间:2015-10-22 08:16:22

标签: java list collections lambda java-8

我有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

但它给了我

%let sheet_list = AG 11, AG 12, ST;

data _null_;
*count with default delimiters for words;
VAR1=countw("&sheet_list");

*count with comma as the dlm;
VAR2=countw("&sheet_list",",");

*count number of commas;
VAR3=countc("&sheet_list",",");

call symputx('words_default',VAR1,'g');
call symputx('words_commas',VAR2,'g');
call symputx('count_commas',VAR3,'g');
run;

%put DEFAULT WORDS: &words_default;
%put COMMAS WORDS: &words_commas;
%put COMMAS COUNT: &count_commas + 1 for words;

由于

1 个答案:

答案 0 :(得分:8)

您不需要使用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());