如何使用Java Stream替代列表索引替换操作中的for循环?
如何用Java Stream替代字符串索引替换的for循环?
我正在学习Java,练习编程逻辑,尝试在集合操作中运用Stream作为最佳实践。现有一个方法接收字符串和Integer类型的List,需将字符串转为列表,根据List中的索引值将对应位置的字符替换为下划线,再转回字符串返回,原代码如下:
private static String wordToGuess(String word,List<Integer> valueUniqueToRemplace){ List<String> wordToList=new ArrayList<>(Arrays.asList(word.split(""))); for (Integer integer : valueUniqueToRemplace) { wordToList.set(integer, "_"); } return wordToList.stream().map(String::valueOf).collect(Collectors.joining("")); }
用Stream重构的实现方案
你可以直接通过IntStream遍历字符串的索引,结合条件判断完成替换,无需先将字符串转为列表再修改,代码更简洁且避免了中间集合的可变操作:
private static String wordToGuess(String word, List<Integer> indicesToReplace) { return IntStream.range(0, word.length()) .mapToObj(index -> indicesToReplace.contains(index) ? "_" : String.valueOf(word.charAt(index))) .collect(Collectors.joining()); }
性能优化建议
如果indicesToReplace中的元素数量较多,List.contains()的时间复杂度是O(n),可以将List转为HashSet来将查询复杂度降为O(1),提升整体性能:
private static String wordToGuess(String word, List<Integer> indicesToReplace) { Set<Integer> replaceIndices = new HashSet<>(indicesToReplace); return IntStream.range(0, word.length()) .mapToObj(index -> replaceIndices.contains(index) ? "_" : String.valueOf(word.charAt(index))) .collect(Collectors.joining()); }
逻辑说明
IntStream.range(0, word.length())生成从0到字符串长度-1的索引流,覆盖字符串的每一个字符位置- 对每个索引,判断是否在需要替换的集合中:是则返回下划线,否则返回原字符的字符串形式
- 最后通过
Collectors.joining()直接将所有字符串片段拼接成最终结果,省去了原代码中修改列表的步骤
内容的提问来源于stack exchange,提问作者Cesar Justo
相关产品推荐
相关产品推荐

