Hello guys, if you have a list of object and you want to conver into Map of object or key value pair then you can use different ways like looping over list and then adding values to map, or you can use Collectors.toMap() by using Stream API, You can even use flatMap() function if you want to convert list of one type of object to Map of another type of object. All this is possible and I will show you code example of how to do that in this article, But, before we get into the process of how you can convert a list of one object to another in Java, let me tell you a bit more about what Java really is.
For those of you who don't know, Java is basically a general-purpose, class-based, object-oriented programming language that aims to have lesser implementation dependencies. You can also think of Java as a computing platform for application development.
What sets Java apart is that it is fast, secure, and reliable. It can be used for developing Java applications with the help of laptops, data centers, game consoles, scientific supercomputers, and even cell phones.
Java was developed by James Gosling when he was working at Sun Microsystems. It was later acquired by the Oracle Corporation.
Java can also be used for developing android applications, creating Enterprise Software, creating mobile java applications, creating scientific computing applications, Big Data analytics, programming hardware devices, and server-side technologies like Apache and GlassFish.
As most of you must know, a List in Java is basically a collection of objects in which duplicates can also be stored. Lists preserve the insertion order, which means that positional access and insertion of new elements are allowed. The list interface in Java can be implemented by ArrayList, LinkedList, Vector, as well as Stack classes.
How To Convert a List to Map in Java? Example
A Java platform is basically a collection of programs that will help you develop and run Java programming applications. It is made up of an execution engine, a compiler, and a set of libraries. It is basically a set of computer software and specifications.Java was developed by James Gosling when he was working at Sun Microsystems. It was later acquired by the Oracle Corporation.
Java can also be used for developing android applications, creating Enterprise Software, creating mobile java applications, creating scientific computing applications, Big Data analytics, programming hardware devices, and server-side technologies like Apache and GlassFish.
As most of you must know, a List in Java is basically a collection of objects in which duplicates can also be stored. Lists preserve the insertion order, which means that positional access and insertion of new elements are allowed. The list interface in Java can be implemented by ArrayList, LinkedList, Vector, as well as Stack classes.
Converting List To Map in Java
Now, I will show you how to convert a List to Map in Java. You
can use the java.util.Map interface in Java for representing a mapping
between a key and a value. One important thing you need to understand is
that the map interface is not a subtype of the collection interface.
This is why it behaves a little bit differently from all the other
collection types.
Check out the following example:
Input: List : [1="1", 2="2", 3="3"] Output: Map : {1=1, 2=2, 3=3} Input: List : [1="People", 2="for", 3="People"] Output: Map : {1=People, 2=for, 3=People}
There are a number of ways to convert a list to a map in Java.
1. By Object Of List and for loop :
// Java program for list convert in map
// with the help of Object method import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.HashMap; // create a list class Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; } } // main class and method public class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<Student>(); // add the member of list lt.add(new Student(1, "Geeks")); lt.add(new Student(2, "For")); lt.add(new Student(3, "Geeks")); // create map with the help of // Object (stu) method // create object of Map class Map<Integer, String> map = new HashMap<>(); // put every value list to Map for (Student stu : lt) { map.put(stu.getId(), stu.getName()); } // print map System.out.println("Map : " + map); } }
2. The Collectors.toMap() method:
You can also use Collectors.toMap() method to convert a list of Object into a Map of keys and values as shown below:
// Java program for list convert in map // with the help of the Collectors.toMap() method import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.stream.Collectors; // create a list class Student { // id will act as Key private Integer id; // name will act as value private String name; // create curstuctor for reference public Student(Integer id, String name) { // assign the value of id and name this.id = id; this.name = name; } // return private variable id public Integer getId() { return id; } // return private variable name public String getName() { return name; } } // main class and method public class GFG { // main Driver public static void main(String[] args) { // create a list List<Student> lt = new ArrayList<>(); // add the member of list lt.add(new Student(1, "Geeks")); lt.add(new Student(2, "For")); lt.add(new Student(3, "Geeks")); // create map with the help of // Collectors.toMap() method LinkedHashMap<Integer, String> map = lt.stream() .collect( Collectors .toMap( Student::getId, Student::getName, (x, y) -> x + ", " + y, LinkedHashMap::new)); // print map map.forEach( (x, y) -> System.out.println(x + "=" + y)); } }
List of Object to Map of Objects using Java 8 FlatMap() Function
If you are using Java 8, you can also use flatmap() to convert a List of object into Map of object as shown in the the following examples:
String[][] array = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}}; // array to a stream Stream<String[]> stream1 = Arrays.stream(array); // same result Stream<String[]> stream2 = Stream.of(array);
It can also be done like this:
[
[a, b],
[c, d],
[e, f]
]
String[][] array = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}}; // convert array to a stream Stream<String[]> stream1 = Arrays.stream(array); List<String[]> result = stream1 .filter(x -> !x.equals("a")) // x is a String[], not String! .collect(Collectors.toList()); System.out.println(result.size()); // 0 result.forEach(System.out::println); // print nothing?It is also possible to refactor the filter method.
String[][] array = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}}; // array to a stream Stream<String[]> stream1 = Arrays.stream(array); // x is a String[] List<String[]> result = stream1 .filter(x -> { for(String s : x){ // really? if(s.equals("a")){ return false; } } return true; }).collect(Collectors.toList()); // print array result.forEach(x -> System.out.println(Arrays.toString(x))); String[][] array = new String[][]{{"a", "b"}, {"c", "d"}, {"e", "f"}}; // Java 8 String[] result = Stream.of(array) // Stream<String[]> .flatMap(Stream::of) // Stream<String> .toArray(String[]::new); // [a, b, c, d, e, f] for (String s : result) { System.out.println(s); }
That's all about how to convert a list of object into map of object in Java. We have seen different ways of converting list to Map in Java like by using a for loop and iterative way, similar to what people do before Java 8 and then we see a new functional way by using Java 8 Stream API and Collectors.toMap() method.
We have also seen an example of using flatMap() which you can use to convert one list of object into a different list of object or a Map of different object. flatmap is like map() Function which can transform one object to another but it can also flatten the list.
Other Java Programming Tutorials you may like:
- Java 8 Comparator Example (check here)
- 5 Free Courses to learn Java 8 and 9 (courses)
- Difference between Stream.map() and Stream.flatMap() in Java 8? (answer)
- 5 Books to Learn Java 8 Better? (read here)
- 10 Advanced Core Java courses for Programmers (courses)
- How to use debug Stream in Java 8 (tutorial)
- Best Courses to learn Java Programming for Beginners (best courses)
- Collection of best Java 8 tutorials (click here)
- 7 best Courses to learn Data structure and Algorithms (best online courses)
- 10 Free Courses for Experienced Java Programmers (courses)
- How to sort the may by values in Java 8? (example)
- How to format/parse the date with LocalDateTime in Java 8? (tutorial)
- Difference between abstract class and interface in Java 8? (answer)
- Top 5 Course to master Java 8 Programming (courses)
If
you liked this article on how you can convert a list of one object to
another in Java, feel free to share it with your friends and family. You
can also drop a comment if you have any doubts about Java and we will
get back to you in an instant.
P.S.- If you just want to learn more about new Stream API in Java 8 and how to use functional programming in Java then you can also see this list of best Java Stream API and collections online training courses for experienced developer. I have shared a couple of really great courses on it which you can use to take your Stream API skill to next level.
No comments:
Post a Comment
Feel free to comment, ask questions if you have any doubt.