How to Remove All LinkedHashMap Values in Java


The example aims to show how to remove/empty/clear all values from LinkedHashMap object in Java.

Source Code

package com.beginner.examples;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashMap;

public class RemoveAllValuesFromJavaLinkedHashMap {

	public static void main(String[] args) {
		
		//create LinkedHashMap.
		LinkedHashMap linkedHashMap = new LinkedHashMap();
		
		linkedHashMap.put("1","Alice");
		linkedHashMap.put("2","Bob");
		linkedHashMap.put("3","Jack");
		
		 Collection  collection1 = linkedHashMap.values();
		 Iterator iterator1= collection1.iterator();
		 System.out.println("Before removal, LinkedHashMap contains :");
		 while(iterator1.hasNext()) {
			 System.out.println(iterator1.next());
		 }
		 
		 /*
		  * To remove all values or clear LinkedHashMap use void clear method() of LinkedHashMap.
		  */
		 linkedHashMap.clear();
		Collection  collection2 = linkedHashMap.values();
		Iterator iterator2= collection2.iterator();
		System.out.println("After removal, LinkedHashMap contains :");
		while(iterator2.hasNext()) {
			System.out.println(iterator2.next());
		}

	}

}

Output:

Before removal, LinkedHashMap contains :
Alice
Bob
Jack
After removal, LinkedHashMap contains :

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments