Java 8– Find first and all longest strings in List
In Java 8, you can find the first and all longest strings from a list using the Stream
API along with the max
function. Here’s an example:
1. Find first longest string
// Find the book has max length
String max1 = books.stream().max(Comparator.comparing(String::length)).get();
//OR
String max2 = Collections.max(books, Comparator.comparing(String::length));
2. Find all longest strings
// Find all books have max length
List<String> maxAll = books.stream().collect(Collectors.groupingBy(String::length))
.entrySet().stream().max(Map.Entry.comparingByKey())
.map(Map.Entry::getValue).get();
//OR
int maxLength = books.stream().mapToInt(String::length).max().orElse(0);
List<String> maxAll2 = books.stream().filter(s -> s.length() == maxLength)
.collect(Collectors.toList());
Similar Post: Java 8– Find first and all smallest string in List
See the complete example.
MaxLenOfBook.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 MaxLenOfBook {
public static void main(String[] args) {
List<String> books = Arrays.asList("Gaban", "Ramayan", "Bhagavat Gita", "Wings Of Fire", "Godan");
// Find the book has max length
String max1 = books.stream().max(Comparator.comparing(String::length)).get();
System.out.println(max1);
//OR
String max2 = Collections.max(books, Comparator.comparing(String::length));
System.out.println(max2);
// Find all books have max length
List<String> maxAll1 = books.stream().collect(Collectors.groupingBy(String::length))
.entrySet().stream().max(Map.Entry.comparingByKey())
.map(Map.Entry::getValue).get();
System.out.println(maxAll1);
//OR
int maxLength = books.stream().mapToInt(String::length).max().orElse(0);
List<String> maxAll2 = books.stream().filter(s -> s.length() == maxLength)
.collect(Collectors.toList());
System.out.println(maxAll2);
}
}
Output:
console.log
Bhagavat Gita
Bhagavat Gita
[Bhagavat Gita, Wings Of Fire]
[Bhagavat Gita, Wings Of Fire]
References
- Java 8 – Count the Occurrences of Character in String
- Java Collections.min() and Collections.max() Methods