Java: Converting lists of one element type to a list of another type

convert list of objects to another list of objects java
convert list of objects to another list of objects java 8
convert list of one type to another java stream
java copy list without reference
java 8 deep copy list
convert type in list java
convert one object to another java
deep copy arraylist java

I'm writing an adapter framework where I need to convert a list of objects from one class to another. I can iterate through the source list to do this as in

Java: Best way of converting List<Integer> to List<String>

However, I'm wondering if there is a way to do this on the fly when the target list is being iterated, so I don't have to iterate through the list twice.

Java 8 way:

List<String> original = ...;
List<Wrapper> converted = original.stream().map(Wrapper::new).collect(Collectors.toList());

assuming Wrapper class has a constructor accepting a String.

How to Clone a List in Java?, How do I convert a list from one type to another in Java? If you want to iterate over a list and create a new list with "transformed" objects, you should use the map() function of stream + collect().In the following example I find all people with the last name "l1" and each person I'm "mapping" to a new Employee instance.

My answer to that question applies to your case:

import com.google.common.collect.Lists;
import com.google.common.base.Functions

List<Integer> integers = Arrays.asList(1, 2, 3, 4);

List<String> strings = Lists.transform(integers, Functions.toStringFunction());

The transformed list is a view on the original collection, so the transformation happens when the destination List is accessed.

How to cast List<Object> to List<MyClass>, <String> strings = mapIntegerToStringCollection(integers); This would be useful is you have to use transformations every time, encapsulating the process. So you can make a library of collection mappers very easy. I have a foreach loop reading a list of objects of one type and producing a list of objects of a different type. I was told that a lambda expression can achieve the same result. var origList = Lis

As an alternative to the iterator pattern, you can use a abstract generic mapper class, and only override the transform method:

  1. create a generic collection mapper for any data type
  2. [optional] create a library of methods that transform between different data types (and override the method)
  3. use that library

the implementation:

// Generic class to transform collections
public abstract class CollectionTransformer<E, F> {

    abstract F transform(E e);

    public List<F> transform(List<E> list) {
        List<F> newList = new ArrayList<F>();
        for (E e : list) {
            newList.add(transform(e));
        }
        return newList;
    }
}

// Method that transform Integer to String
// this override the transform method to specify the transformation
public static List<String> mapIntegerToStringCollection(List<Integer> list) {

    CollectionTransformer transformer = new CollectionTransformer<Integer, String>() {
        @Override  
        String transform(Integer e) {
            return e.toString();
        }
    };
    return transformer.transform(list);
}

// Example Usage
List<Integer> integers = Arrays.asList(1,2);
List<String> strings = mapIntegerToStringCollection(integers);

This would be useful is you have to use transformations every time, encapsulating the process. So you can make a library of collection mappers very easy.

How to compare two ArrayList for equality in Java?, of the class objects from an array using the asList method. In Java, there are various methods to clone a list. This article will explain some of the main methods used to achieve the same. Using a Copy Constructor: Using the ArrayList constructor in Java, a new list can be initialized with the elements from another collection.

You can write a mapping iterator that decorates an existing iterator and applies a function on it. In this case, the function transforms the objects from one type to another "on-the-fly".

Something like this:

import java.util.*;

abstract class Transformer<T, U> implements Iterable<U>, Iterator<U> {
    public abstract U apply(T object);  

    final Iterator<T> source;       
    Transformer(Iterable<T> source)    { this.source = source.iterator(); }

    @Override public boolean hasNext() { return source.hasNext(); }
    @Override public U next()          { return apply(source.next()); }
    @Override public void remove()     { source.remove(); } 

    public Iterator<U> iterator()      { return this; }
}

public class TransformingIterator { 
    public static void main(String args[]) {
        List<String> list = Arrays.asList("1", "2", "3");
        Iterable<Integer> it = new Transformer<String, Integer>(list) {
            @Override public Integer apply(String s) {
                return Integer.parseInt(s);
            }
        };
        for (int i : it) {
            System.out.println(i);
        }
    }
}

Copy a List to Another List in Java, How do you cast a list of objects in Java? The get() method of List interface in Java is used to get the element present in this list at a given specific index.. Syntax : E get(int index) Where, E is the type of element maintained by this List container.

Lambdaj allows to do that in a very simple and readable way. For example, supposing you have a list of Integer and you want to convert them in the corresponding String representation you could write something like that;

List<Integer> ints = asList(1, 2, 3, 4);
Iterator<String> stringIterator = convertIterator(ints, new Converter<Integer, String> {
    public String convert(Integer i) { return Integer.toString(i); }
});

Lambdaj applies the conversion function only while you're iterating on the result. There is also a more concise way to use the same feature. The next example works supposing that you have a list of persons with a name property and you want to convert that list in an iterator of person's names.

Iterator<String> namesIterator = convertIterator(persons, on(Person.class).getName());

Pretty easy. Isn't it?

Java List, object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false. First, lists are immutable, which means elements of a list cannot be changed by assignment. Second, lists represent a linked list whereas arrays are flat. The type of a list that has elements of type T is written as List[T]. Try the following example, here are few lists defined for various data types.

ArrayList to Array Conversion in Java : toArray() Methods , Due to the fact that we're copying reference here and not cloning the objects, every amends made in one element will affect both lists. For that  Converting a List to String in Java. Last modified One of the simplest ways is to simply call the method of the type of the elements within the List.

Chapter 10. Arrays, Insert All Elements From One List Into Another; Get Elements From a Java List; Find Elements in a List All Elements From One List in Another; List Size; Sublist of List; Convert List to Set Without a generic type set on the List variable declaration the Java The resulting List is the union of the two lists. If the passed array doesn’t have enough space, a new array is created with same type and size of given list. If the passed array has more space, the array is first filled with list elements, then null values are filled. It throws ArrayStoreException if the runtime type of a is not a supertype of the runtime type of every element in this list.

Top 10 Mistakes Java Developers Make, Note: toArray() method returns an array of type Object(Object[]). It is therefore recommended to create an array into which elements of List need to See your article appearing on the GeeksforGeeks main page and help other Geeks. and Run-time Polymorphism in Java · How to iterate over a 2D list (list of lists) in Java. Now in this R programming DataFlair tutorial series, we will see one of the major R data types that is R list in detail. First of all, we will learn about R list, then we will discuss how to create, access and modify lists in R with the help of examples.

Comments
  • what if in place of Integer and String, we have custom classes ?
  • This looks close to what I'm looking for. As per the similar response, does doing this on the fly give me much advantage?
  • Honestly, I think the Google Collections solution (Ben Lings') might be better. Their design is a lot more mature, and their implementation is more robust. Frankly I just whipped that code up in 15 minutes without putting too much thought into it.
  • I mean, the class implements Iterator<U> and Iterable<U>. I'm not sure if that's kosher.
  • Indeed, a bad idea for generalized collections.
  • Isn't the list iterated (at least) twice; once on the original list when the conversion is done and then again when the target list is iterated over?