How to initialize a HashMap in Java

This article shows different ways to initialize HashMap in Java. Initialize a HashMap (Standard) Collections.singletonMap Java 9 Map.of Java 9 Map.ofEntries Create a function to return a Map Static Initializer Java 8, Stream of SimpleEntry Conclusion After initialized a HashMap, the result is either a mutable map or an immutable map: Mutable map – It …

Read more

Java 8 – Convert Optional<String> to String

In Java 8, we can use .map(Object::toString) to convert an Optional<String> to a String. String result = list.stream() .filter(x -> x.length() == 1) .findFirst() // returns Optional .map(Object::toString) .orElse(""); Samples A standard Optional way to get a value. Java8Example1.java package com.mkyong; import java.util.Arrays; import java.util.List; import java.util.Optional; public class Java8Example1 { public static void main(String[] …

Read more

Java Map with Insertion Order

In Java, we can use LinkedHashMap to keep the insertion order. P.S HashMap does not guarantee insertion order. 1. HashMap Generate a HashMap, UUID as key, index 0, 1, 2, 3, 4… as value. JavaHashMap.java package com.mkyong.samples; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.stream.IntStream; public class JavaHashMap { public static void main(String[] args) { …

Read more

Java 8 forEach print with Index

A simple Java 8 tip to print the Array or List with index in the front. 1. Array with Index Generate the index with IntStream.range. JavaListWithIndex.java package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class JavaArrayWithIndex { public static void main(String[] args) { String[] names = {"Java", "Node", "JavaScript", "Rust", "Go"}; List<String> collect = …

Read more

Java – How to get keys and values from Map

In Java, we can get the keys and values via map.entrySet() Map<String, String> map = new HashMap<>(); // Get keys and values for (Map.Entry<String, String> entry : map.entrySet()) { String k = entry.getKey(); String v = entry.getValue(); System.out.println("Key: " + k + ", Value: " + v); } // Java 8 map.forEach((k, v) -> { …

Read more

Java – How to Iterate a HashMap

In Java, there are 3 ways to loop or iterate a HashMap 1. If possible, always uses the Java 8 forEach. Map<String, String> map = new HashMap<>(); map.forEach((key, value) -> System.out.println("[Key] : " + key + " [Value] : " + value)); 2. Normal for loop in entrySet() Map<String, String> map = new HashMap<>(); for …

Read more

Java 8 Streams map() examples

In Java 8, stream().map() lets you convert an object to something else. Review the following examples : 1. A List of Strings to Uppercase 1.1 Simple Java example to convert a list of Strings to upper case. TestJava8.java package com.mkyong.java8; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class TestJava8 { public static void …

Read more

Java – Convert Object to Map example

In Java, you can use the Jackson library to convert a Java object into a Map easily. 1. Get Jackson pom.xml <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.3</version> </dependency> 2. Convert Object to Map 2.1 A Jackson 2 example to convert a Student object into a java.util.Map Student.java package com.mkyong.examples; import java.util.List; public class Student { private String …

Read more

Java – Display all ZoneId and its UTC offset

A Java 8 example to display all the ZoneId and its OffSet hours and minutes. P.S Tested with Java 8 and 12 1. Display ZoneId and Offset DisplayZoneAndOffSet.java package com.mkyong; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; public class DisplayZoneAndOffSet { public static final boolean SORT_BY_REGION = false; …

Read more

Java 8 – How to sort a Map

Java 8 Stream examples to sort a Map, by keys or by values. 1. Quick Explanation Steps to sort a Map in Java 8. Convert a Map into a Stream Sort it Collect and return a new LinkedHashMap (keep the order) Map result = map.entrySet().stream() .sorted(Map.Entry.comparingByKey()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); P.S By …

Read more

Java 8 – Convert Map to List

Few Java examples to convert a Map to a List Map<String, String> map = new HashMap<>(); // Convert all Map keys to a List List<String> result = new ArrayList(map.keySet()); // Convert all Map values to a List List<String> result2 = new ArrayList(map.values()); // Java 8, Convert all Map keys to a List List<String> result3 = …

Read more

JUnit – How to test a Map

Forget about JUnit assertEquals(), to test a Map, uses the more expressive IsMapContaining class from hamcrest-library.jar pom.xml <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency> <!– This will get hamcrest-core automatically –> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <version>1.3</version> <scope>test</scope> </dependency> </dependencies> 1. IsMapContaining Examples All the below assertThat checks will be passed. …

Read more

Java 8 – Convert List to Map

Few Java 8 examples to show you how to convert a List of objects into a Map, and how to handle the duplicated keys. Hosting.java package com.mkyong.java8 public class Hosting { private int Id; private String name; private long websites; public Hosting(int id, String name, long websites) { Id = id; this.name = name; this.websites …

Read more

How to get the environment variables in Java

In Java, the System.getenv() returns an unmodifiable string Map view of the current system environment. Map<String, String> env = System.getenv(); // get PATH environment variable String path = System.getenv("PATH"); Table of contents. 1. Get a specified environment variable 2. UnsupportedOperationException 3. Display all environment variables 4. Sort the environment variables 5. Download Source Code 6. …

Read more

Java – Check if key exists in HashMap

In Java, you can use Map.containsKey() to check if a key exists in a Map. TestMap.java package com.mkyong.examples; import java.util.HashMap; import java.util.Map; public class TestMap { public static void main(String[] args) { Map<String, Integer> fruits = new HashMap<>(); fruits.put("apple", 1); fruits.put("orange", 2); fruits.put("banana", 3); fruits.put("watermelon", null); System.out.println("1. Is key ‘apple’ exists?"); if (fruits.containsKey("apple")) { //key …

Read more

How to count duplicated items in Java List

A Java example to show you how to count the total number of duplicated entries in a List, using Collections.frequency and Map. CountDuplicatedList.java package com.mkyong; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class CountDuplicatedList { public static void main(String[] args) { List<String> list = new …

Read more

Convert JSON string to Map using Jackson

This article uses the Jackson framework to parse JSON strings to a Map in Java. Table of contents: 1. Download Jackson 2. Convert JSON string to Map 3. Convert Map to JSON string 4. Download Source Code 5. References P.S Tested with Jackson 2.17.0 1. Download Jackson Simply declare jackson-databind in the pom.xml, and it …

Read more

Spring EL Lists, Maps example

In this article, we show you how to use Spring EL to get value from Map and List. Actually, the way of SpEL works with Map and List is exactly same with Java. See example : //get map whete key = ‘MapA’ @Value("#{testBean.map[‘MapA’]}") private String mapA; //get first value from list, list is 0-based. @Value("#{testBean.list[0]}") …

Read more

How to sort a Map in Java

Few Java examples to sort a Map by its keys or values. Note If you are using Java 8, refer to this article – How to use Stream APIs to sort a Map 1. Sort by Key 1.1 Uses java.util.TreeMap, it will sort the Map by keys automatically. SortByKeyExample1.java package com.mkyong.test; import java.util.HashMap; import java.util.Map; …

Read more

Java – How to display all System properties

In Java, you can use System.getProperties() to get all the system properties. Properties properties = System.getProperties(); properties.forEach((k, v) -> System.out.println(k + ":" + v)); // Java 8 1. Example DisplayApp.java package com.mkyong.display; import java.util.Properties; public class DisplayApp { public static void main(String[] args) { Properties properties = System.getProperties(); // Java 8 properties.forEach((k, v) -> System.out.println(k …

Read more