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

1 minute read

This is a method to easily retrieve the maximum length string stored in ArrayList<String>. If you think normally, it is to turn it with for and get the one that lenght becomes Max, Here we use stream to get in one line.

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 total ordering). This will return the maximum value compared by Comparator.

  • Comparator.comparing(String::length)

Specify the String type length as the key for comparison. This will compare the lengths of the strings.

  • .get()

Returns the value.

Therefore, String type can be compared and the maximum value can be returned. ‥

Test code (bonus)

This is the verified test code. From now on, instead of using public static void main(String…strings) as an example, I also want to use the test code as an example, while also learning 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
    String with maximum length in void ArrayList_String_ () {
        StringList stringList = new StringList();
        stringList = new StringList();
        stringList.add("");
        stringList.add("12345");
        stringList.add("1234567890");
        String str = stringList.maxString();
        assertThat("1234567890", is(str));
    }
}