Convenient use of Map that you do not know unexpectedly

Use of collection

It is an exaggeration to say that it is almost essential to use collections such as List, Map, and Set when programming in Java. Among them, Map can manage data in the key-value format, so it is often used in scenes such as acquiring data in advance, packing it in Map, and reusing it.

In particular, Java 8 has added Stream API, lambda expressions, Optional, etc. to make collections easier to use. But did you know that behind these additional features are a lot of useful methods added? Here are some useful methods.

Get the initial value when data cannot be obtained! (getOrDefaut)

Suppose you have a map that holds points that can be used at the store for each membership code.

Map<String, Integer> pointMap = new HashMap<>();

In the case of logic that wants to return 0 points when a member does not hold points, it can be obtained by writing as follows.

int point = 0;

//Get points if you hold points
if (pointMap.containsKey(code)) {
    point = pointMap.get(code);
}

It's troublesome and not beautiful to judge each time. That's where getOrDefault comes in.

int point = pointMap.getOrDefault(code, 0);

You could write it in one line neatly. You can write code like this when you want to get a value if the map doesn't have a value.

Set only if you do not hold the value! (putIfAbsent)

Suppose you write a logic that gives points only to members who do not have points yet for the point information.

//If you do not hold points, give points
if (!pointMap.containsKey(code)) {
    pointMap.put(code, point);
}

From Java 8, you can write this as follows:

pointMap.putIfAbsent(code, point);

In this code, point is set only when there is no point associated with the member.

If the value is not held, set the initial value! (computeIfAbsent)

Suppose you have a Map that adds and holds a history of a student's test scores.

Map<String, List<Integer>> scoreMap = new HashMap<>();

If there are students who already have a score, add a new score as a history after that score.

List<Integer> scores = scoreMap.get(code);

//If the student's score has not yet been recorded
if (scores == null) {
    //Create a list for a new history
    scores = new ArrayList<>();
    scoreMap.put(code, scores);
}

scores.add(score);

If you cannot get it from Map, you need to set List and add points to that List. You can write this using computeIfAbsent as follows:

scoreMap.computeIfAbsent(code, k -> new ArrayList<>()).add(score);

If no student test results are retained, create a new List, and if there are already results, return the existing List. Since the points are added to the List returned as it is, it will be possible to write in one line.

Manipulate values when they are retained! (computeIfPresent)

Suppose you have a map that holds the number of days attended by students who attended a class, and the student code of the student taking the class and the number of days attended 0 are entered by default.

Map<String, Integer> attendanceMap = new HashMap<>();

If students do not take classes but come, they will be ignored, and students who are taking classes will increase the number of attendance days by one.

if (attendanceMap.containsKey(code)) {
    attendanceMap.put(code, attendanceMap.get(code) + 1) ;
}

You can write this using computeIfPresent as follows:

attendanceMap.computeIfPresent(code, (k, v) -> v + 1);

computeIfPresent does nothing if the student code does not have the corresponding attendance days, and can only increase the value (attendance days) if there is the corresponding student.

Summary

Java 8 has added a lot of features such as Stream and lambda expressions, but in fact there are many more useful features. It's good to search the net for the API you need when you need it, but it's also interesting to read the official API docs as you would read a dictionary.

Recommended Posts

Convenient use of Map that you do not know unexpectedly
Java reserved word summary that you do not know unexpectedly
Do you need a memory-aware implementation of Java?
Do you need dotenv-rails?
Convenient use of Map that you do not know unexpectedly
[Java] The difference between the Stream.of () and Arrays.stream () methods that you do not know unexpectedly
Do you know Decorator?
How to replace characters that you do not understand [Principle]
Programs that use io_uring do not work with Docker on CentOS 8
[Java] Do not use "+" in append!
Do you use Stream in Java?
How do you write in Scala that was written in Java? (List → Map)
How to make @Transactional work that does not work if you use it incorrectly
[Spring Boot] If you use Spring Boot, it was convenient to use a lot of util.
Do you use the for statement after all? Do you use a while statement? Proper use of for statement and while statement