Thursday, 3 March 2022

Dozer: Map collection of objects

Right now I do not see a direct way to map collection of objects. But using the below generic method, we can convert collection of objects.

public static <T, U> List<U> map(final Mapper mapper, final List<T> source, final Class<U> destType) {

	final List<U> dest = new ArrayList<>();

	for (T element : source) {
		dest.add(mapper.map(element, destType));
	}

	return dest;
}

 


 

Find the below working application.

 

Type1.java

package com.sample.app.model;

public class Type1 {
	private int a;
	private int b;

	public Type1() {
	}

	public Type1(int a, int b) {
		this.a = a;
		this.b = b;
	}

	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}

	public int getB() {
		return b;
	}

	public void setB(int b) {
		this.b = b;
	}

	@Override
	public String toString() {
		return "Type1 [a=" + a + ", b=" + b + "]";
	}

}

Type2.java

package com.sample.app.model;

public class Type2 {
	private int a;
	private int b;

	public Type2() {
	}

	public Type2(int a, int b) {
		this.a = a;
		this.b = b;
	}

	public int getA() {
		return a;
	}

	public void setA(int a) {
		this.a = a;
	}

	public int getB() {
		return b;
	}

	public void setB(int b) {
		this.b = b;
	}

	@Override
	public String toString() {
		return "Type2 [a=" + a + ", b=" + b + "]";
	}

}

MapCollectionsDemo.java

package com.sample.app;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.dozer.DozerBeanMapper;
import org.dozer.Mapper;

import com.sample.app.model.Type1;
import com.sample.app.model.Type2;

public class MapCollectionsDemo {

	public static <T, U> List<U> map(final Mapper mapper, final List<T> source, final Class<U> destType) {

		final List<U> dest = new ArrayList<>();

		for (T element : source) {
			dest.add(mapper.map(element, destType));
		}

		return dest;
	}

	public static void main(String args[]) {
		Type1 type1 = new Type1(10, 50);
		Type1 type2 = new Type1(20, 60);
		Type1 type3 = new Type1(30, 70);
		Type1 type4 = new Type1(40, 80);

		List<Type1> type1Objects = Arrays.asList(type1, type2, type3, type4);

		DozerBeanMapper mapper = new DozerBeanMapper();

		List<Type2> type2Objects = map(mapper, type1Objects, Type2.class);

		System.out.println("Printing Type1 objects");
		type1Objects.stream().forEach(System.out::println);

		System.out.println("\n\nPrinting Type2 objects");
		type2Objects.stream().forEach(System.out::println);

	}

}

Output

Printing Type1 objects
Type1 [a=10, b=50]
Type1 [a=20, b=60]
Type1 [a=30, b=70]
Type1 [a=40, b=80]


Printing Type2 objects
Type2 [a=10, b=50]
Type2 [a=20, b=60]
Type2 [a=30, b=70]
Type2 [a=40, b=80]



 

Previous                                                 Next                                                 Home

No comments:

Post a Comment