gpt4 book ai didi

Java 8 : Converting an array of strings to have first character in uppercase and sorted order

转载 作者:行者123 更新时间:2023-12-01 17:51:02 25 4
gpt4 key购买 nike

我有一个字符串数组,例如:

String[] strArray = { "Red", "green", "Blue", "Yellow", "violet", "magenta", "pURPLE" };

我希望将其转换为数组,以便给定数组中的所有字符串的第一个字符均为大写。预期输出应该是:

[Blue, Green, Magenta, PURPLE, Red, Violet, Yellow]

最后应该对数组进行排序(这很容易,只需添加 sorted() 操作)。

我正在尝试这个,但它不起作用:

System.out.println(Arrays.stream(strArray)
.map((String x) -> {x=(x != null ? (x.substring(0,1).toUpperCase() + x.substring(1, x.length())) : "");})
.sorted()
.collect(Collectors.toList()));

我收到此错误:

The method map(Function<? super String,? extends R>) in the type Stream<String> is not applicable for the arguments ((String x) -> {})

我确信我错过了一些小事情,但我无法弄清楚是什么。

最佳答案

您可以使用Character.toUpperCase()方法用于此。

System.out.println(Arrays.stream(strArray)
.filter(Objects::nonNull)
.map(s->Character.toUpperCase(s.charAt(0))+ s.substring(1))
.sorted()
.collect(Collectors.toList()));

关于Java 8 : Converting an array of strings to have first character in uppercase and sorted order,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50073174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com