gpt4 book ai didi

java - 如何使用流比较字符串字符?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:00:43 25 4
gpt4 key购买 nike

我在研究流,我遇到了一个问题。我有一个列表,我需要按字符串的长度排序,所有匹配大写字符的字符串,如果没有,则按字母排序。

List<String> phones = new ArrayList<>();
Collections.addAll(phones, "iPhone X", "Nokia 9", "Huawei Nexus 6P",
"Samsung Galaxy S8", "LG G6", "Xiaomi MI6", "Sony Xperia Z5",
"Asus Zenfone 3", "Meizu Pro 6", "Heizu Pro 6",
"pixel 2");

phones.stream().filter(s -> s.matches("A-Z")).sorted(Comparator.comparingInt(String::length)).forEach(System.out::println);

我尝试使用匹配,但我在某处犯了一个错误,因为没有任何输出。我该如何解决这个问题?

最佳答案

几乎没有什么可以补救的,您需要确保有两种不同的字符串分类,一种有大写字母,另一种没有。为此,您可以将列表划分为:

Map<Boolean, List<String>> partitionedValues = phones.stream()
.collect(Collectors.partitioningBy(a -> containsUpperCase(a)));

containsUpperCase 实现看起来像这样:

boolean containsUpperCase(String value) {
for (char ch : value.toCharArray()) {
if (Character.isUpperCase(ch)) {
return true;
}
}
return false;
}

一旦您对数据进行了分区,您需要将它们聚合到一个最终列表中,如下所示:

List<String> finalOutput = partitionedValues.get(Boolean.TRUE) // with upper case
.stream()
.sorted(Comparator.comparing(String::length)) // sorted by length
.collect(Collectors.toList());

finalOutput.addAll(partitionedValues.get(Boolean.FALSE) // without uppercase
.stream()
.sorted(Comparator.naturalOrder()) // sorted naturally
.collect(Collectors.toList()));

您的最终输出将显示为:

finalOutput.forEach(System.out::println);

关于java - 如何使用流比较字符串字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54274684/

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