Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform List<X> to another List<Y> [duplicate]

I have two lists of objects; List<X> and List<Y>. X and Y are ojects that look like:

public class X {     String a;     String b;     String v;     String w;     String m;     String n; }  public class Y {     String a;     String b;     List<A> aList; } public class A {     String v;     String w;     List<B> bList; } public class B {     String m;     String n; } 

How transform List<X> into List<Y> based on a rule:
Some fields' values must be equal.
For example:
In List<Y>, for one object Y, field a's value must equal.
In Y's field List<A>, for one object A, field w's value must equal.
In A's field List<B>, for one object B, field m's value must equal and so on.

Guava has this method, Lists#transform, but I don't know how to transform.

Or any other way?

like image 836
zhm Avatar asked Sep 12 '11 05:09

zhm


People also ask

How do I convert a list to a different list?

Thus, converting the whole list into a list of lists. Use another list 'res' and a for a loop. Using split() method of Python we extract each element from the list in the form of the list itself and append it to 'res'. Finally, return 'res'.

How do I convert a list from one list to another in Java?

Another approach to copying elements is using the addAll method: List<Integer> copy = new ArrayList<>(); copy. addAll(list); It's important to keep in mind whenever using this method that, as with the constructor, the contents of both lists will reference the same objects.

How do I clone a list?

To clone a list, one can iterate through the original list and use the clone method to copy all the list elements and use the add method to append them to the list. Approach: Create a cloneable class, which has the clone method overridden. Create a list of the class objects from an array using the asList method.


1 Answers

public static <F,T> List<T> transform(List<F> fromList,                                       Function<? super F,? extends T> function 

You might want to read up the API docs for Lists.transform() and Function, but basically the caller of the transform provides a Function object that converts an F to a T.

For example if you have a List<Integer> intList and you want to create a List<String> such that each element of the latter contains the english representation of that number (1 becomes "one" etc) and you have a access to a class such as IntToEnglish then

Function<Integer, String> intToEnglish =      new Function<Integer,String>() {          public String apply(Integer i) { return new IntToEnglish().english_number(i); }     };  List<String> wordsList = Lists.transform(intList, intToEnglish); 

Does that conversion.

You can apply the same pattern to transform your List<X> to List<Y>

like image 129
Miserable Variable Avatar answered Oct 25 '22 07:10

Miserable Variable