[Creating] A memorandum about coding in Java

About string comparison

** When checking if a string matches a string in Java, it is strictly forbidden to use the == operator! Use the equals method! ** **

Notes on the equals method

・ Exception occurs when hoge is null in hoge.equals (“Hello”) ・ *** Exceptions can be prevented by bringing the value first, such as “Hello” .equals (hoge), or by determining hoge! = Null ***

comment

How to write

For one line
//comment
For multiple lines
/*
*comment
*/

About Javadoc

How to write

/**
 *Description (Summary explanation + Detailed explanation)
 *
 * block tags...(Block tag)
 */

Tag description

A description of the @param parameter (argument). @return A description of the return value. @author A description of the author of the program. @throw A description of the exception that is thrown.

References

About comment types Basic knowledge of Javadoc How to write Javadoc documentation comments

Map

What is Map?

There is a "key" for each value, and the "key" and "value" are paired.

How to use

Must be initialized with HashMap.

To declare a Map object using the HashMap class, write as follows.

Java


Map<Key model name,Value type name>Object name= new HashMap<>();

Add element with put

Describe as follows.

Java


Map type object name.put(Key,value);

Get element with get

Java


Map type object name.get(Key);

How to process Map elements in a loop

Loop processing with for, foreach

When handling the data registered in Map in a batch, it is common to process it in a loop.

Java does not have a foreach instruction, but it has the same processing method as foreach in other languages.

It is called an extended for statement.

Describe as follows.

Java


for(Type variable name:List name){
    System.out.println(Variable name);
}
Loop processing with iterator

You can also write loop processing using a mechanism called Iterator.

Describe as follows.

Java


for(Iterator<Map.Entry<Key model name,Value type name>> iterator = map.entrySet().iterator() ; iterator.hasNext() ;){
    Map.Entry<Key model name,Value type name> entry = iterator.next();
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

Get and search the key value of Map

Get key with keySet

Unlike arrays and Lists, Maps have a mechanism called "keys".

To get only the name of the "key" in the Map, use the keySet method.

Describe as follows.

Java


Map type object name.keySet()
Search for key with containsKey

Use the containsKey method to determine if a particular "key" is included in the Map.

Describe as follows.

Java


Map type object name.containsKey(Key to search)

Ternary conditional operator

How to use

Conditional expression?Equation 1:Equation 2

Evaluates the conditional expression and returns expression 1 if it is true and expression 2 if it is false. One thing to keep in mind when writing the conditional operator is to make the data types of Expression 1 and Expression 2 the same. This is because it is inconvenient if the data types returned by TRUE (true) and FALSE (false) in the conditional expression are different, because some numerical value or character is returned as a result of the conditional expression.

The specific program is as follows.

Implementation example

ConditionalTest.java


/* ConditionalTest */
public class ConditionalTest {
    public static void main(String[] args) {
        int i = 2;
        int j = 3;
        int k = (i > j) ? 4 : 0;

        System.out.println("k = " + k);

        System.out.println("i = " + i);
        System.out.println((i >= j) ? "i is 3 or more" : "i is 3 or less");
    }
}

Compile and run results

C:\java>java ConditionalTest
k = 0
i = 2
i is 3 or less

How to fill with zeros

Use the format function. Reference: http://write-remember.com/program/java/format/

Description method

Use Description example Remarks
Fill the beginning of the string with spaces String.format("%6s", "abc") Adds a blank character to the left of the specified character string up to 6 digits.
Fill in the blanks after the string String.format("%-6s", "abc") Adds an empty string to the right of the specified character string up to 6 digits.
Fill the beginning of the number with 0 String.format("%06d", 123) Zero-pads the specified number to the left of the string up to 6 digits.
Separate numbers by commas every 3 digits String.format("%,d", 123456789) Separates the specified numbers into commas every 3 digits

How to use

** Set the number of digits (6 digits ("% 6s") in the example below) in the first argument, Set the target character string in the second argument. ** **

Implementation example

test.java


public void formatTest2() {
    //Expected value
    String expected = "123";
    //000123 is assigned to result
    String result = String.format("%6s", "123").replace(" ", "0");

How to use Stream API

filter It is an intermediate operation. The argument is a lambda expression that is T-> boolean. Collect only elements whose expression is true.

forEach For the argument of forEach, pass a lambda expression such as (T)-> void. This is a termination operation that takes out elements one by one and performs some processing. Please refer to the following for how to use.

Implementation example

Only if the list has a start time and an end time, do end time-start time, The example is a method that sets a value for the required time.

calculateDuration.java


    protected List<String> calculateDuration(
            List<String> list) {
        list.stream()
        //Narrow down to those with both start time and end time set
        .filter(i -> !Strings.isEmpty(i.getTimeStart()) && !Strings.isEmpty(i.getTimeFin()))
         //End time-Subtract the start time and set it to the required time
        .forEach(i -> {
            String duration = Integer.toString(Integer.parseInt(i.getTimeFin()) - Integer.parseInt(i.getTimeStart()));
            i.setDuration(duration);
        });
        return list;
    }

Recommended Posts

[Creating] A memorandum about coding in Java
About returning a reference in a Java Getter
Creating a matrix class in Java Part 1
Creating a matrix class in Java Part 2-About matrices (linear algebra)-
webApi memorandum in java
A story about the JDK in the Java 11 era
A note about Java GC
Find a subset in Java
About Alibaba Java Coding Guidelines
About abstract classes in java
3 Implement a simple interpreter in Java
I created a PDF in Java.
A simple sample callback in Java
About file copy processing in Java
Creating lexical analysis in Java 8 (Part 2)
Get stuck in a Java primer
Creating lexical analysis in Java 8 (Part 1)
Java memorandum
About what I did when creating a .clj file in Clojure
JAVA memorandum
Member description order in Java coding convention
What is a class in Java language (3 /?)
Java creates a table in a Word document
Java creates a pie chart in Excel
What is a class in Java language (1 /?)
What is a class in Java language (2 /?)
Create a TODO app in Java 7 Create Header
About Records preview added in Java JDK 14
How to implement coding conventions in Java
Try making a calculator app in Java
Creating a Servlet in the Liberty environment
Continued Talk about writing Java in Emacs @ 2018
Implement something like a stack in Java
Split a string with ". (Dot)" in Java
Creating a project (and GitHub repository) using Java and Gradle in IntelliJ IDEA
A story about a Spring Boot project written in Java that supports Kotlin
I made a primality test program in Java
GetInstance () from a @Singleton class in Groovy from Java
About Java interface
Add .gitignore when creating a project in Xcode
[Java] About Java 12 features
Escape processing when creating a URL in Ruby
About the confusion seen in startup Java servers
Two ways to start a thread in Java + @
Read a string in a PDF file with Java
Create a CSR with extended information in Java
About the idea of anonymous classes in Java
Partization in Java
[Java] About arrays
How to display a web page in Java
[Android / Java] Operate a local database in Room
Java memorandum (list)
Measure the size of a folder in Java
Code to escape a JSON string in Java
Try to create a bulletin board in Java
Changes in Java 11
About var used in Java (Local Variable Type)
Rock-paper-scissors in Java
A note when you want Tuple in Java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
Something about java