簡體   English   中英

如何在ArrayList中大寫每個元素的第一個字符並刪除?

[英]How to capitalize the first character of each element AND delete in an ArrayList?

我正在嘗試迭代以大寫我的數組列表中以“m”而不是 M 開頭的所有第一個字符,並刪除所有不以 m 或 M 開頭的字符。我在這里嘗試了一個似乎對我有幫助的代碼刪除了幾個詞,但不是我想要的詞,並且沒有按照我的需要大寫這些詞。 這就是我如何記下我添加的一些代碼

    int i = 0;
    int j = 0;
    for (i = 0; i < myNameList.size(); i++) {

        String name = myNameList.get(i);
        String[] names = name.split("\\s+");
        StringBuilder sb = new StringBuilder();

        for (j = 0; j < names.length; j++) {
            if (j != 0) {
                sb.append(' ');
            }

            sb.append(Character.toUpperCase(names[j].charAt(0)));
            sb.append(names[j].substring(1).toLowerCase());
        }
        if (names[0] == "m") {
            myNameList.set(i, sb.toString());
        } else if ((names[0] != "m" && names[0] != "M")) {
            myNameList.remove(i);
        }
    }//end for loop
    System.out.println(myNameList);

結果:在插入之前輸入你想輸入的名字List 插入Melbourne Mackay Mermaid Beach Maitland Maroochydore Muwoolimbah Merriwether monkeytown Troydon [Mackay, Maitland, Muwoolimbah, monkeytown]
刪除后列表 Mackay Maitland Muwoolimbah monkeytown

移除后

            else if ((names[0] != "m" || names[0] != "M")) {
            myNameList.remove(i);
        }

插入前列表墨爾本麥凱美人魚海灘梅特蘭 Maroochydore Muwoolimbah Merriwether monkeytown Troydon [Melbourne, Mackay, Mermaid Beach, Maitland, Maroochydore, Muwoolimbah, Merriwether, Monkeytown, Troydon]
刪除后列表 墨爾本 Mackay Mermaid Beach Maitland Maroochydore Muwoolimbah Merriwether Monkeytown Troydon

您可以先過濾列表,只包含以 m/M 開頭的單詞。
然后大寫第一個字母,最后收集到列表。

List<String> cleanList = list.stream()
    .filter(s -> s.startsWith("m") || s.startsWith("M"))
    .map(s -> s.startsWith("m")
        ? "M" + s.substring(1) : s)
    .collect(Collectors.toList());

您應該避免硬編碼“m”,如下所示:

完整示例

public static void main(String[] args) {
    List<String> list = List.of("man", "Many", "notM");
    System.out.println(cleanList(list, 'm'));
}

private static List<String> cleanList(List<String> list, char letter) {
    return list.stream()
            .filter(s -> Character.toUpperCase(s.charAt(0)) == Character.toUpperCase(letter))
            .map(s -> Character.isLowerCase(s.charAt(0))
                    ? Character.toUpperCase(s.charAt(0)) + s.substring(1) : s)
            .collect(Collectors.toList());
}

輸出

[男人,很多]

一個更簡單的方法是

for (String name : myNameList) {

    String str = name.replaceAll("^m", "M");  // replace beginning `m` with `M`
    if (str.charAt(0) == 'M')
    {
        newList.add (str);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM