使用 Java 8 在句子中按长度查找第二大字符串

发布: (2026年3月23日 GMT+8 19:16)
1 分钟阅读
原文: Dev.to

Source: Dev.to

Java 代码

import java.util.Arrays;
import java.util.Comparator;
import java.util.Optional;

public class SecondLargestString {
    public static void main(String[] args) {
        String sentence = "The quick brown fox jumps over the lazy dog";

        Optional secondLargest = Arrays.stream(sentence.split("\\s+")) // 1. Split into words
            .distinct() // 2. Remove duplicates (e.g., "The" and "the" would be treated as distinct here unless lowercased first)
            .sorted(Comparator.comparingInt(String::length).reversed() // 3. Sort by length in descending order
                .thenComparing(Comparator.naturalOrder())) // 4. Optional: sort alphabetically for ties in length
            .skip(1) // 5. Skip the longest string
            .findFirst(); // 6. Get the next string (the second longest)

        if (secondLargest.isPresent()) {
            System.out.println("The second largest string is: " + secondLargest.get());
        } else {
            System.out.println("Could not find the second largest string.");
        }
    }
}
0 浏览
Back to Blog

相关文章

阅读更多 »

两数之和 - Java

使用哈希解决 Two Sum 我的思考过程 当我第一次看到 Two Sum 问题时,我的初始想法很简单: - 目标 = 9 - 当前数字 = 2 我不需要…

SJF4J:Java 的结构化 JSON 门面

介绍 在 Java 中使用 JSON 通常意味着在两种方式之间进行选择: - 数据绑定 POJO —— 强类型,但刚性 - 树模型 JsonNode / Ma...

下一个排列

问题描述:任务是计算给定数字数组的下一个排列。排列是相同元素的重新排列,而下一个…