Created
May 10, 2020 14:49
-
-
Save SanthoshBabuMR/b0449d107fe93ab3d6e3c2b1e5b11028 to your computer and use it in GitHub Desktop.
HashMap to List (java)
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
import java.util.*; | |
public class HashMapToList { | |
public static void main(String[] args) { | |
HashMapToList hashMapToList = new HashMapToList(); | |
hashMapToList.init(); | |
} | |
private void init() { | |
List<User> users = toList(getData()); | |
System.out.println(users); | |
} | |
private Map<User, List<User>> getData() { | |
Map<User, List<User>> data = new HashMap<>(); | |
User kushina = new User(10, "Kushina", null ); | |
User naruto = new User(11, "Naruto", 10 ); | |
data.put(kushina, Arrays.asList(naruto)); | |
User sangeetha = new User(20, "Sangeetha", null ); | |
User sanjay = new User(21, "Sanjay Vijay", 20 ); | |
User divya = new User(22, "Divya Saasha Vijay", 20 ); | |
data.put(sangeetha, Arrays.asList(sanjay, divya)); | |
User jyothika = new User(30, "Jyothika", null ); | |
User diya = new User(31, "Diya Suriya", 30 ); | |
User dev = new User(31, "Dev Suriya", 30 ); | |
data.put(jyothika, Arrays.asList(dev, diya)); | |
return data; | |
} | |
private List<User> toList(Map<User, List<User>> usersMap) { | |
List<User> users = new ArrayList<>(); | |
usersMap.entrySet().stream().forEach(entry -> { | |
User parent = entry.getKey(); | |
List<User> children = entry.getValue(); | |
children.stream().forEach(child -> { | |
child.setParentName(parent.getName()); | |
users.add(child); | |
}); | |
}); | |
return users; | |
} | |
} | |
class User { | |
int id; | |
String name; | |
Integer parentId; | |
String parentName; | |
public User(int id, String name, Integer parentId) { | |
this.id = id; | |
this.name = name; | |
this.parentId = parentId; | |
} | |
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; | |
} | |
public Integer getParentId() { | |
return parentId; | |
} | |
public void setParentId(Integer parentId) { | |
this.parentId = parentId; | |
} | |
public String getParentName() { | |
return parentName; | |
} | |
public void setParentName(String parentName) { | |
this.parentName = parentName; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment