Posts

Showing posts with the label HashMap

How to get keys and values from Map in Java?

In this section, we will show you h ow to get keys and values from Map in Java. Java 8 Example import java.util.HashMap ; import java.util.Map ; public class Main { public static void main ( String [] args) { Map < String , String > map = new HashMap<>(); map .put( "host" , "knowledgefactory.net" ); map .put( "username" , "knowledgefactory" ); map .put( "password" , "mypassword" ); // Java 8 map .forEach((k, v) -> { System . out .println( "Key: " + k + ", Value: " + v); }); } } Console Output: Key: password, Value: mypassword Key: host, Value: knowledgefactory.net Key: username, Value: knowledgefactory Old style import java.util.Collection ; import java.util.HashMap ; import java.util.Map ; import java.util.Set ; public class Main { public static void main ( String [] args) { Map < String , String > ...

How to transform HashMap to another HashMap using Java 8 Collectors toMap

Image
Hello everyone, here we will show you how to convert HashMap<Integer, User> to another HashMap<Integer, UserDto> using Java 8 Collectors toMap. The  Collectors.toMap returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements. Overview of components used in this example Java Stream API The Java Stream API provides a functional approach to processing collections of objects. The Stream in Java can be defined as a sequence of elements from a source Collection or Array. Most of the stream operations return a Stream. This helps create a chain of stream operations(stream pipe-lining). The streams also support the aggregate or terminal operations on the elements. for example, finding the minimum or maximum element or finding average etc...Stream operations can either be executed sequentially or parallel. when performed parallelly, it is called a parallel stream. Collect...