Close

How to find the longest and the shortest String in Java?

[Updated: Apr 22, 2020, Created: Apr 22, 2020]

Java String Manipulation Java Collections Java 

This tutorial shows different ways of finding longest and shortest string in Java.

Using a loop

package com.logicbig.example;

import java.util.Arrays;
import java.util.List;

public class ShortestLongestStrings {
  public static void main(String[] args) {
      List<String> fruits = Arrays.asList("apple", "banana", "pie", "pineapple", "apricots");
      String longestFruitName = "";
      for (String fruit : fruits) {
          if (fruit.length() > longestFruitName.length()) {
              longestFruitName = fruit;
          }
      }

      String shortestFruitName = longestFruitName;
      for (String fruit : fruits) {
          if (fruit.length() < shortestFruitName.length()) {
              shortestFruitName = fruit;
          }
      }

      System.out.println("Longest Fruit name: " + longestFruitName);
      System.out.println("Shortest Fruit name: " + shortestFruitName);
  }
}
Longest Fruit name: pineapple
Shortest Fruit name: pie

Via Sorting by Length

package com.logicbig.example;

import java.util.*;

public class ShortestLongestStrings2 {
  public static void main(String[] args) {
      List<String> fruits = Arrays.asList("apple", "banana", "pie", "pineapple", "apricots");
      List<String> sortedList = new ArrayList<>(fruits);
      Collections.sort(sortedList, Comparator.comparingInt(String::length));

      System.out.println("Longest Fruit name: " + sortedList.get(sortedList.size() - 1));
      System.out.println("Shortest Fruit name: " + sortedList.get(0));
  }
}
Longest Fruit name: pineapple
Shortest Fruit name: pie

By using Java 8 Streams

package com.logicbig.example;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class ShortestLongestStrings3 {
  public static void main(String[] args) {
      List<String> fruits = Arrays.asList("apple", "banana", "pie", "pineapple", "apricots");

      String shortestFruitName = fruits.stream()
                                       .sorted(Comparator.comparingInt(String::length))
                                       .findFirst()
                                       .orElse(null);

      String longestFruitName = fruits.stream()
                                      .sorted(Comparator.comparingInt(String::length))
                                      .reduce((first, second) -> second)
                                      .orElse(null);

      System.out.println("Longest Fruit name: " + longestFruitName);
      System.out.println("Shortest Fruit name: " + shortestFruitName);
  }
}
Longest Fruit name: pineapple
Shortest Fruit name: pie

See Also