singhakash
singhakash

Reputation: 7919

Convert List<MyObject> to List<List<String>> using java8 lambdas only

I have List<User> where User is a class having variable id,name,date .I just want to create a List<List<String>> with it such that it only contains name and date from the first list.My Code

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

  }
}

I cant seem to figure out how can I achieve that when I use collect()it says cannot find the symbol on collect. Is there any way I can get List<List<String>> containing List of name and date from List<User>

I also tried

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());

But it gave me

 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

Thanks

Upvotes: 3

Views: 6817

Answers (1)

Eran
Eran

Reputation: 393811

You don't need to use an IntStream.

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

EDIT:

If you wish to stay with the IntStream solution :

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());

Upvotes: 8

Related Questions