gpt4 book ai didi

java - 返回存在字母的字符串的总和 - 使用流

转载 作者:行者123 更新时间:2023-11-30 02:39:39 25 4
gpt4 key购买 nike

我有一个包含单词(编程语言)的列表,我想找出这些单词中存在字母表中的哪个字母,然后将这些单词的总字符串长度相加,最后返回其中的一个字母返回与这些单词匹配的最长字符串。这是我到目前为止所得到的,而且我几乎没有进一步了解。

这是我试图更好地理解 java 流的一个练习。

package com.example;

import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class DemoApplicationTests {

@Test
public void argh() {

List<String> list = new ArrayList<>();
list.add("java");
list.add("php");
list.add("python");
list.add("perl");
list.add("c");
list.add("lisp");
list.add("c#");

Supplier<Stream<String>> streamSupplier = () -> list.stream();
IntStream.range('a', 'z').forEach(i -> {
int strlen = streamSupplier.get()
.filter(k -> {
char ch = (char) i;
return k.contains("" + ch);
}
)
.map(s -> s.length())
.mapToInt(Integer::new)
.sum();
System.out.println((char) i + " : " + strlen);
}
);
}
}

我期望的最终输出(结果)就像“p:17”

由于字符“p”出现在单词 php、python、perl、lisp 中,因此它对这些单词求和并返回字符串长度 17。

最好是在

map<String,int> with the size of 1

或者其他东西,只包含最长的字符串。

这里有一些伪代码,说明我如何用“普通”java 编写它:

int previousSum = 0;
for (string ch in ('a' to 'z') ) {
int stringlengthSum = findallMatchesInListandSumStringlength(stringlist,ch);
if (stringlengthSum > previousSum) {
previousSum = stringLengthSum;
longestCharacter = ch;
}
}
System.out.println("The longest sum is: " + previousSum + " by the character: " + longestcharacter);

最佳答案

我必须稍微更改和优化您的代码。最终的解决方案是:

Map.Entry<Integer, Integer> max = IntStream.range('a', 'z').boxed().collect(Collectors.toMap(i -> i, i -> list.stream()
.filter(k -> k.contains("" + (char) i.intValue()))
.map(String::length)
.mapToInt(Integer::new)
.sum()))
.entrySet().stream()
.max((e1, e2) -> e1.getValue().compareTo(e2.getValue())).get();

System.out.println((char)max.getKey().intValue() + ":" + max.getValue());

变化是:

1) 转换 IntStreamStream<Integer>以便能够从中收集 map

2) 收集对:符号的 int 值 -> 具有该符号的单词的总和

并且至少 3)找到其中包含最大元素的映射条目

关于java - 返回存在字母的字符串的总和 - 使用流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42108857/

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