[Java] How to easily get the longest character string of ArrayList using stream

This is an easy way to retrieve the longest string stored in ArrayList \ . If you think about it normally, you can turn it with for to get the one whose lenght becomes Max. Here, stream is used to get it in one line </ strong> </ font>.

Note) stream is available in Java 8 or later.

Source code

maxString () is the method to get the maximum string length.

StringList.java



package samples.stream.main;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class StringList {
    private List<String> _strList = new ArrayList<String>();

    public void add(String str) {
        _strList.add(str);
    }

    public String maxString() {
        return _strList.stream().max(Comparator.comparing(String::length)).get();
    }
}

Commentary

  • max(

Returns the maximum element of the specified Comparator (comparison function that performs global ordering). This will return the maximum value compared by Comparator.

  • Comparator.comparing(String::length)

Specify the length of String type as the key for comparison. This will compare by string length.

  • .get()

Returns a value.

Therefore, String type length can be compared and the maximum value can be returned </ strong> </ font>.

Test code (bonus)

This is the verified test code. From now on, instead of exemplifying with public static void main (String ... strings) I would like to use a test code as an example to learn TDD.

StreamMaxTest.java



package samples.stream.test;

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;

import org.junit.jupiter.api.Test;

import samples.stream.main.StringList;

class StreamMaxTest {
    @Test
    void ArrayList_String_Maximum length of the string() {
        StringList stringList = new StringList();
        stringList = new StringList();
        stringList.add("");
        stringList.add("12345");
        stringList.add("1234567890");
        String str = stringList.maxString();
        assertThat("1234567890", is(str));
    }
}

Recommended Posts