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?
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'.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With