gpt4 book ai didi

java - 无论如何,是否可以设置取决于流链内流的结果的值

转载 作者:行者123 更新时间:2023-11-30 05:41:56 26 4
gpt4 key购买 nike

我需要编写一个将返回指定控制台输出的流链。

我设法获得了正确的结果,但我不得不打破我的流链,我想知道是否有任何方法可以避免它

public class Main {
public static void main(String[] args) throws IOException {
Map<String, List<String>> map;
int maxValue;
map = new BufferedReader(
new InputStreamReader(
new URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt")
.openStream(), StandardCharsets.UTF_8))
.lines().flatMap(Pattern.compile("[\\r\\n]")::splitAsStream)
.collect(Collectors.groupingBy(s -> Stream.of(s.split(""))
.sorted().collect(Collectors.joining()), Collectors.toList()));

maxValue = map.values().stream().mapToInt(List::size).max().getAsInt();

map.values().stream().filter(l -> l.size() == maxValue).collect(Collectors.toList())
.stream().sorted(Comparator.comparing(s -> s.get(0))).collect(Collectors.toList()).
forEach(n -> System.out.println(n.stream().sorted().collect(Collectors.joining(" "))));
}
}

我希望获得与代码中相同的结果,但不应将 maxValue 设置在流链外部,而应将其设置在内部。

最佳答案

您可以使用 TreeMap 及其最后一个条目来收集所有最大值:

new BufferedReader(new InputStreamReader(new URL("http://wiki.puzzlers.org/pub/wordlists/unixdict.txt").openStream(), StandardCharsets.UTF_8))
.lines()
.collect(Collectors.groupingBy(s -> Stream.of(s.split("")).sorted().collect(Collectors.joining()), Collectors.toList()))
.entrySet().stream()
.collect(Collectors.groupingBy(e -> e.getValue().size(), TreeMap::new, Collectors.toList()))
.lastEntry().getValue()
.stream().map(Map.Entry::getValue)
.sorted(Comparator.comparing(s -> s.get(0)))
.map(n -> n.stream().sorted().collect(Collectors.joining(" ")))
.forEach(System.out::println);

关于java - 无论如何,是否可以设置取决于流链内流的结果的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55481801/

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