Last active
December 17, 2015 10:58
-
-
Save golonzovsky/5598325 to your computer and use it in GitHub Desktop.
fill types of target list from sourse list ones with same name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.test; | |
import static org.junit.Assert.assertEquals; | |
import static org.junit.Assert.assertNull; | |
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import org.junit.Before; | |
import org.junit.Test; | |
public class TwoTypeArrayTest { | |
private static final String TYPE1 = "type"; | |
private List<ClassA> listA = new ArrayList<ClassA>(); | |
private List<ClassB> listB = new ArrayList<ClassB>(); | |
private ClassB b1; | |
private ClassB b2; | |
@Before | |
public void setup(){ | |
listA.add(new ClassA("name1", TYPE1)); | |
listA.add(new ClassA("name2", "type2")); | |
b1 = new ClassB("name1", null); | |
listB.add(b1); | |
b2 = new ClassB("name3", null); | |
listB.add(b2); | |
} | |
@Test | |
public void testAssignment() { | |
fillTypes(listA, listB); | |
assertEquals(TYPE1, b1.getType()); | |
assertNull(b2.getType()); | |
} | |
private void fillTypes(List<ClassA> source, List<ClassB> target){ | |
final Map<String, String> sourceMap = new HashMap<String, String>(); | |
for (ClassA sourceObj : source) { | |
sourceMap.put(sourceObj.getName(), sourceObj.getType()); | |
} | |
for (ClassB targetObj : target) { | |
final String name = targetObj.getName(); | |
if (sourceMap.containsKey(name)){ | |
targetObj.setType(sourceMap.get(name)); | |
} | |
} | |
} | |
} | |
class ClassB{ | |
private String name; | |
private String type; | |
ClassB(String name, String type) { | |
this.name = name; | |
this.type = type; | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public String getType() { | |
return type; | |
} | |
public void setType(String type) { | |
this.type = type; | |
} | |
} | |
class ClassA{ | |
private String name; | |
private String type; | |
ClassA(String name, String type) { | |
this.name = name; | |
this.type = type; | |
} | |
public String getName() { | |
return name; | |
} | |
public void setName(String name) { | |
this.name = name; | |
} | |
public String getType() { | |
return type; | |
} | |
public void setType(String type) { | |
this.type = type; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment