gpt4 book ai didi

java - 如何使用Java中的流来比较和操作一个列表中的两个相邻元素?

转载 作者:行者123 更新时间:2023-12-02 01:42:21 30 4
gpt4 key购买 nike

背景是我有两个字符串类型变量str1和str2作为输入。最后我必须返回一个列表,其中包含 str1 的连续前缀小于 str2 中的相关前缀。

我有这样的Java代码:

public List<Character> getPrefix(String str1, String str2) {
int index = 0;
List<Character> res = new ArrayList<>();
//str1 = "1243"
//str2 = "2324"
// The answer will be "12".

while (index < str1.length() && index < str2.length() && str1.charAt(index) <= str2.charAt(index)) {
res.add(str1.charAt(index));
index++;
}

return res;
}
//the return type could either be List<String> or List<Character>

我被要求在流中转换此代码,而不使用 while 或 for 循环,只是在流方法中。我打算像这样转换这段代码

List<String> list = new ArrayList<>();
list.add(str1);
list.add(str2);
List<String> res = list.stream()
.filter()
.reduce();

我发现filter()方法可以选择与给定谓词匹配的元素,而reduce()方法可以使用identity和accumulator来获得最终结果。

但是我发现我既没有办法操作一个列表中的两个相邻元素,也没有办法得到一个指针来比较和遍历列表中每个元素中的每个字符(该元素是String类型)。

有什么方法可以操作一个列表中的两个相邻元素,以便我可以比较它们在同一位置的字符。

最佳答案

你可以:

  1. 生成索引流
  2. 使用索引获取两个字符串的字符
  3. 选择有效的字符

    // The magic
    public static List<Character> getPrefix(String str1, String str2) {

    return IntStream
    .range(0, Math.min(str1.length(), str2.length()))
    .mapToObj(i -> new char[] { str1.charAt(i), str2.charAt(i) })
    .takeWhile(a -> a[0] < a[1])
    .map(a -> a[0])
    .collect(Collectors.toList());

    }

关于java - 如何使用Java中的流来比较和操作一个列表中的两个相邻元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54281775/

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