SoFunction
Updated on 2025-04-08

Detailed explanation of methods in Java

Preface

In Java programming, the Map interface is a very important collection type, which stores key-value pairs. With the release of Java 8, many new default methods have been introduced in the interface, one of which is getOrDefault(). This method provides developers with a concise way to access elements in a map and can return a default value when a given key does not exist. This article will introduce in detail the working principle, usage and some practical application scenarios of the getOrDefault() method.

getOrDefault()The formal definition of the method is as follows:

default V getOrDefault(Object key, V defaultValue)
  • key: This is the key you want to find.
  • defaultValue: If the key does not have a corresponding value, this parameter specifies the default value that should be returned.

Working mechanism

When you call(key, defaultValue)When  , first check whether there are entries associated with the key in the map. If such an entry exists, its value will be returned; conversely, if no matching key is found, the passed defaultValue will be directly returned.

This method avoids the verbose code that may traditionally be written, such as first using containsKey() to determine whether a key is contained, and then decide whether to obtain the value or use the default value based on the result. This simplification not only makes the code more concise and easy to read, but also reduces potential sources of errors.

Practical application cases

Suppose we have an application that counts the number of clicks from a website user. We can use HashMap<String, Integer> to store each user ID and its corresponding number of clicks. However, until the behavior of a new user is first recorded, the user's ID will not appear in our map. At this time, getOrDefault() can come in handy:

Map&lt;String, Integer&gt; userClicks = new HashMap&lt;&gt;();
// Suppose there is some logical processing here...int userIdClicks = (userId, 0);
(userId, userIdClicks + 1);

In this example, for a new user ID, getOrDefault() ensures that the ID can be correctly initialized to 0 even if it has not existed in the map, and then incremented this value. This way we can safely update all users' click data without worrying about null pointer exceptions or similar errors.

Performance considerations

Although getOrDefault() provides great convenience, it still needs to be used with caution in performance-sensitive application scenarios. Especially when defaultValue is computationally expensive, frequent call to this method may result in unnecessary overhead. Therefore, the relationship between simplicity and efficiency should be weighed when designing a system.

Anyway,()It is an extremely useful feature introduced by Java 8. It simplifies the process of retrieving data from mappings and is able to gracefully handle missing keys. Making this feature rationally can help developers write clearer and more reliable programs. As your experience grows, you will find more suitable situations for applying getOrDefault(), thereby further improving your programming skills.

Attachment: Algorithm Question

Question: Except for two numbers in an integer array, all other numbers appear twice. Please write a program to find these two numbers that only appear once.

Code:

import .*;
class Main {
	public static void FindNumsAppearOnce(int [] array) {
        int res=0;
        boolean flag=true;
        Map<Integer,Integer> map=new HashMap();
        for(int i=0;i<;i++){
            (array[i], (array[i], 0) + 1);       
        }
        for(int j=0;j<;j++){
        if((array[j])==1&&flag==true){
            (array[j]);
            flag=false;
        }  
        else if((array[j])==1&&flag==false){
            (array[j]);
        }  
    }
}
	public static void main(String[] args) {
		int a[]={2,2,3,3,4,6,5,5};
		FindNumsAppearOnce(a);
	}
}

Summarize

This is the end of this article about the detailed explanation of the () method in Java. For more related contents of the () method in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!