1

I have two Lists

List<String> a = Arrays.asList( "1" , "2" , "3" );
List<String> b = Arrays.asList( "a" , "b" , "c" );

and a class

class Obj{
   String a;
   String b;
   public Obj(String a, String b){
       this.a=a;
       this.b=b;
   }
}

I have to convert every element 2 lists into an object of above class. Resulting into a list of object of Obj in something like this -

[ Obj("1","a") , Obj("2","a") , Obj("3","a") ]

I know i can do it simply by running a loop.

List<Obj> arrayList = new ArrayList<>();

for( int i=0; i<allAttributes.size(); i++){
    arrayList.add( new Obj(a[i],b[i]) );
}

Wanted to know if it can be done in Java 8 some elegant way.

Naman
  • 27,789
  • 26
  • 218
  • 353
rishabhjainps
  • 410
  • 1
  • 5
  • 14

2 Answers2

3

Given that a and b lists are of same size, this should do the trick,

List<Obj> objList = IntStream.range(0, a.size())
    .mapToObj(i -> new Obj(a.get(i), b.get(i)))
    .collect(Collectors.toList());
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
0

There are a few ways to implement a Zip-Operation for lists and streams (see this post for example), but you could use the existing method com.google.common.collect.Streams.zip in Guava Streams. That way, your code could look like this:

final List<String> a = Arrays.asList("1", "2", "3");
final List<String> b = Arrays.asList("a", "b", "c");
List<Obj> objs = Streams.zip(a.stream(), b.stream(), (pa, pb) -> new Obj(pa, pb))
            .collect(Collectors.toList());

You can further filter the stream afterwards, e.g.:

List<Obj> objs = Streams.zip(a.stream(), b.stream(), (pa, pb) -> new Obj(pa, pb))
            .filter(obj -> StringUtils.isNotEmpty(obj.b))
            .collect(Collectors.toList());
sfiss
  • 2,119
  • 13
  • 19