Home » Java programming language

Java LinkedHashMap removeEldestEntry() Method with Example

LinkedHashMap Class removeEldestEntry() method: Here, we are going to learn about the removeEldestEntry() method of LinkedHashMap Class with its syntax and example.
Submitted by Preeti Jain, on March 09, 2020

LinkedHashMap Class removeEldestEntry() method

  • removeEldestEntry() method is available in java.util package.
  • removeEldestEntry() method is used to check whether the eldest entry is to be removed or not.
  • removeEldestEntry() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • removeEldestEntry() method does not throw an exception at the time of removing the older entry.

Syntax:

    public boolean removeEldestEntry(Map.Entry ele_entry);

Parameter(s):

  • Map.Entry ele_entry – represents the eldest entry or least recently entry to be removed from this LinkedHashMap.

Return value:

The return type of the method is boolean, it returns true when the eldest entry should be deleted from the Map otherwise it returns false.

Example:

// Java program to demonstrate the example 
// of boolean removeEldestEntry(Map.Entry ele_entry)
// method of  LinkedHashMap 

import java.util.*;

public class RemoveEldestEntryOfLinkedHashMap {
    public static void main(String[] args) {
        final int MAX_S = 5;

        // Instantiates a LinkedHashMap object
        Map < Integer, String > map = new LinkedHashMap < Integer, String > () {
            protected boolean removeEldestEntry(Map.Entry < Integer, String > eldest) {
                return size() > MAX_S;
            }
        };

        // By using put() method is to add
        // key-value pairs in a LinkedHashMap
        map.put(10, "C");
        map.put(20, "C++");
        map.put(50, "JAVA");
        map.put(40, "PHP");
        map.put(30, "SFDC");

        //Display LinkedHashMap
        System.out.println("LinkedHashMap: " + map);

        // By using removeEldestEntry() method is to
        // remove the eldest entry and inserted new 
        // one in this LinkedHashMap
        map.put(60, "ANDROID");

        //Display LinkedHashMap
        System.out.println("LinkedHashMap: " + map);
    }
}

Output

LinkedHashMap: {10=C, 20=C++, 50=JAVA, 40=PHP, 30=SFDC}
LinkedHashMap: {20=C++, 50=JAVA, 40=PHP, 30=SFDC, 60=ANDROID}



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.