You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java中对Arrays.asList生成的字符串列表排序并处理首字母大写

Java: Capitalize Names and Case-Insensitive Sort with Streams

Hey there! Let's get this code sorted out (pun intended) and break down all the moving parts here. First, we'll complete the missing capitalize method, then optimize the code to be more idiomatic with Java Streams instead of that clunky for-loop.

Complete & Optimized Code

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CapitalizeAndSort {
    public static void main(String[] args) {
        List<String> topNames2017 = Arrays.asList(
            "Amelia", "Olivia", "emily", "Isla", "Ava", "oliver", "Jack", "Charlie", "harry", "Jacob"
        );

        // Chain Stream operations to capitalize + sort in one go
        List<String> sortedCapitalizedNames = topNames2017.stream()
            .map(CapitalizeAndSort::capitalize) // Capitalize each name
            .sorted(String.CASE_INSENSITIVE_ORDER) // Case-insensitive sort
            .collect(Collectors.toList()); // Collect results into a new List

        // Print to verify output
        sortedCapitalizedNames.forEach(System.out::println);
    }

    // Helper method to capitalize names (with edge case handling)
    private static String capitalize(String name) {
        // Handle null or empty strings to avoid exceptions
        if (name == null || name.isEmpty()) {
            return name;
        }
        // Capitalize first character, make rest lowercase for consistent formatting
        return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
    }
}

Key Code Explanations

1. The capitalize Method

  • We added edge case handling for null or empty strings to prevent StringIndexOutOfBoundsException.
  • The method converts the first character to uppercase, then the rest to lowercase—this ensures consistent formatting even if input has mixed cases (e.g., "eMiLy" becomes "Emily").

2. Stream Optimization

  • Instead of modifying the original list with a for-loop, we use Stream.map() to apply the capitalize function to every element. This follows functional programming principles (no side effects, immutable data).
  • sorted(String.CASE_INSENSITIVE_ORDER) uses Java's pre-built comparator for case-insensitive sorting—this is cleaner than writing a custom lambda, though (s1, s2) -> s1.compareToIgnoreCase(s2) would work too.
  • Collectors.toList() replaces the old toArray(String[]::new) + Arrays.asList() combo—it's more readable and directly returns a mutable List<String>.

Common Technical Questions Answered

  • Q: Why can't I just modify the original Arrays.asList list directly?
    A: Arrays.asList() returns a fixed-size list backed by the original array. You can use set() to change elements, but you can't add/remove elements (it throws UnsupportedOperationException). Using streams to generate a new list is safer and more maintainable.

  • Q: What's the difference between String.CASE_INSENSITIVE_ORDER and compareToIgnoreCase?
    A: They're functionally identical! String.CASE_INSENSITIVE_ORDER is a pre-defined Comparator whose compare() method internally calls compareToIgnoreCase(). Using the pre-built comparator makes code more readable.

  • Q: Why convert the rest of the string to lowercase in capitalize?
    A: It ensures consistent formatting. If we only capitalized the first letter, inputs like "oLiVeR" would become "OLiVeR"—not exactly the clean, standardized name format we want. Lowercasing the rest fixes that.

内容的提问来源于stack exchange,提问作者Mirza Celik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:25:21