Java 8– Find first and all smallest string in List


Using the Java 8 Stream API min method, you can find the first and all smallest strings from a List. Here’s an example:

1. Find the first smallest string

// Find the book has a min length
String min1 = books.stream().min(Comparator.comparing(String::length)).get();

//OR
String min2 = Collections.min(books, Comparator.comparing(String::length));

2. Find all the smallest strings

// Find all books that have min length
List<String> minAll = books.stream().collect(Collectors.groupingBy(String::length))
        .entrySet().stream().min(Map.Entry.comparingByKey())
        .map(Map.Entry::getValue).get();

//OR
int minLength = books.stream().mapToInt(String::length).min().orElse(0);
List<String>minAll2 = books.stream().filter(s -> s.length() == minLength)
        .collect(Collectors.toList());

Similar Post: Java 8– Find first and all longest strings in List

See the complete example.

MinLenOfBook.java
package org.websparrow;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class MinLenOfBook {

    public static void main(String[] args) {

        List<String> books = Arrays.asList("Gaban", "Ramayan", "Bhagavat Gita", "Wings Of Fire", "Godan");

        // Find the book has a min length
        String min1 = books.stream().min(Comparator.comparing(String::length)).get();
        System.out.println(min1);
        //OR
        String min2 = Collections.min(books, Comparator.comparing(String::length));
        System.out.println(min2);

        // Find all books have min length
        List<String> minAll1 = books.stream().collect(Collectors.groupingBy(String::length))
                .entrySet().stream().min(Map.Entry.comparingByKey())
                .map(Map.Entry::getValue).get();
        System.out.println(minAll1);
        //OR
        int minLength = books.stream().mapToInt(String::length).min().orElse(0);
        List<String> minAll2 = books.stream().filter(s -> s.length() == minLength)
                .collect(Collectors.toList());
        System.out.println(minAll2);
    }
}

Output:

console.log
Gaban
Gaban
[Gaban, Godan]
[Gaban, Godan]

References

  1. Java 8 – Count the Occurrences of Character in String
  2. Java Collections.min() and Collections.max() Methods

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.