I have a table in my SQL Server 2012 Database as follows:
Student:
ID, CardNo, Name, ZipCode, city, ...
I'm writing a Java desktop application using JDK 8, in which I want to put selected rows from this table in a HashMap
with CardNo
as key and Name
as value.
What's the efficient way to fill this HashMap
using a lambda expression?
Note: CardNo
is unique.
These key/value pairs are also called map entries. In the below example, we can populate a Map using a lambda expression. We have passed Character and Runnable arguments to Map object and pass a lambda expression as the second argument in the put () method of Map class.
Java 8 Object Oriented Programming Programming To initialize a HashMap with Lambda, at first create a HashMpa and use Callable − HashMap<Integer, Callable<Integer>>map = newHashMap<Integer, Callable<Integer>> () For key-value pair, you need to initialize them in the following way −
A lambda expression is one or more line of code which works like function or method. It takes a parameter and returns the value. Lambda expression can be used to convert ArrayList to HashMap.
A lambda expression is one or more line of code which works like function or method. It takes a parameter and returns the value. Lambda expression can be used to convert ArrayList to HashMap. Below is the implementation of the above approach. Time Complexity: O (N), where N is the length of Arraylist.
Here is a simpler way:
List<Student> students = xxxDao.retrieveStudents();
Map<Integer, String> map = students.stream()
.collect(Collectors.toMap(Student::getCardNo, Student::getName));
Also, you could add a static import for Collectors.toMap
and make the expression even more readable.
How about this:
List<Student> students = xxxDao.findFromDB();
Map<String, String> map = students.stream().collect(
Collectors.groupingBy(Student::getCardNo,
Collectors.collectingAndThen(
Collectors.mapping(Student::getName,
Collectors.toList()), nameList->nameList.get(0))));
-------------------------------------------------------split line------------------------------------------------------------------
This way I give above is much rather complex, and thanks to the @FedericoPeraltaSchaffner, there is other more simple way to express what we want. Since CardNo
is unique, just use Collectors.toMap
List<Student> students = xxxDao.findFromDB();
Map<String, String> map = students.stream().collect(Collectors.toMap(Student::getCardNo, Student::getName));
Why use a lambda? Keep it simple:
ResultSet resultSet = stmt.executeQuery(query); // assuming this
Map<String, String> map = new HashMap<>();
while(resultSet.next())
map.put(resultSet.getString("CardNo"), resultSet.getString("Name"));
Using streams/lambdas is not automatically the best option, as here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With