* BAEL-2018

* Update Animal.java

* rename
This commit is contained in:
myluckagain
2018-07-20 00:07:00 +05:00
committed by Predrag Maric
parent a5b49fb919
commit 770e8b0219
3 changed files with 152 additions and 0 deletions
@@ -0,0 +1,27 @@
package com.baeldung.convertlisttomap;
public class Animal {
private int id;
private String name;
public Animal(int id, String name) {
this.id = id;
this.setName(name);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@@ -0,0 +1,52 @@
package com.baeldung.convertlisttomap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.collections4.MapUtils;
import com.google.common.collect.Maps;
public class ConvertListToMapService {
public Map<Integer, Animal> convertListBeforeJava8(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<Integer, Animal>();
for (Animal animal : list) {
map.put(animal.getId(), animal);
}
return map;
}
public Map<Integer, Animal> convertListAfterJava8(List<Animal> list) {
Map<Integer, Animal> map = list.stream().collect(Collectors.toMap(Animal::getId, animal -> animal));
return map;
}
public Map<Integer, Animal> convertListWithGuava(List<Animal> list) {
Map<Integer, Animal> map = Maps.uniqueIndex(list, Animal::getId);
return map;
}
public Map<Integer, Animal> convertListWithApacheCommons1(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<Integer, Animal>();
IterableUtils.forEach(list, animal -> {
map.put(animal.getId(), animal);
});
return map;
}
public Map<Integer, Animal> convertListWithApacheCommons2(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<Integer, Animal>();
MapUtils.populateMap(map, list, Animal::getId);
return map;
}
}