This is an easy way to retrieve the longest string stored in ArrayList \
Note) stream is available in Java 8 or later.
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();
}
}
Returns the maximum element of the specified Comparator (comparison function that performs global ordering). This will return the maximum value compared by Comparator.
Specify the length of String type as the key for comparison. This will compare by string length.
Returns a value.
Therefore, String type length can be compared and the maximum value can be returned </ strong> </ font>.
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