使用 Stream 将 ScoreItemTableSourceVO 列表转换为 List<List<Object>>
<h2>使用 Stream 将 ScoreItemTableSourceVO 列表转换为 List<List<Object>></h2>
<p>以下代码展示了如何使用 Java Stream API 将 ScoreItemTableSourceVO 列表转换为 List<List<Object>>,并对原始代码进行了优化,使其更简洁易懂。</p>
<p><strong>原始代码:</strong></p>
<pre><code class="language-java">final List<List<Object>> list = ListUtils.newArrayList();
//excel表格内容
for (final ScoreItemTableSourceVO scoreItemTableSourceVO : scoreItemTableSourceVOS) {
final List<Object> data = ListUtils.newArrayList();
data.add(DutyClassifyEnum.getDutyClassifyEnum(d -> d.getValue() == scoreItemTableSourceVO.getDutyClassifySort(),
DutyClassifyEnum::getName, () -> null));
data.add(scoreItemTableSourceVO.getAssessee());
data.add(scoreItemTableSourceVO.getTotalScore());
final List<ScoreItemValueVO> scoreList = scoreItemTableSourceVO.getScoreList();
if (CollectionUtils.isNotEmpty(scoreList)) {
for (final ScoreItemValueVO scoreItemValueVO : scoreList) {
data.add(scoreItemValueVO.getAssessScore());
}
}
list.add(data);
}
</code></pre>
<p><strong>使用 Stream 优化后的代码:</strong></p>
<pre><code class="language-java">List<List<Object>> list = scoreItemTableSourceVOS.stream()
.map(scoreItemTableSourceVO -> {
List<Object> data = new ArrayList<>();
data.add(DutyClassifyEnum.getDutyClassifyEnum(d -> d.getValue() == scoreItemTableSourceVO.getDutyClassifySort(),
DutyClassifyEnum::getName, () -> null));
data.add(scoreItemTableSourceVO.getAssessee());
data.add(scoreItemTableSourceVO.getTotalScore());
List<ScoreItemValueVO> scoreList = scoreItemTableSourceVO.getScoreList();
if (CollectionUtils.isNotEmpty(scoreList)) {
scoreList.stream()
.map(ScoreItemValueVO::getAssessScore)
.forEach(data::add);
}
return data;
})
.collect(Collectors.toList());
</code></pre>
<p><strong>代码解释:</strong></p>
<ol>
<li>使用 <code>scoreItemTableSourceVOS.stream()</code> 创建一个 Stream 对象,用于遍历 ScoreItemTableSourceVO 列表。</li>
<li>使用 <code>map</code> 方法将每个 ScoreItemTableSourceVO 对象转换为一个 List<Object> 对象。</li>
<li>在 <code>map</code> 方法中,我们首先创建一个新的 ArrayList<Object> 对象,然后将 ScoreItemTableSourceVO 的各个属性添加到该列表中。</li>
<li>如果 ScoreItemTableSourceVO 包含一个 ScoreItemValueVO 列表,则使用 <code>scoreList.stream().map(ScoreItemValueVO::getAssessScore).forEach(data::add)</code> 将 ScoreItemValueVO 列表中每个元素的 assessScore 属性添加到 List<Object> 对象中。</li>
<li>最后,使用 <code>collect(Collectors.toList())</code> 方法将所有的 List<Object> 对象收集到一个 List<List<Object>> 对象中。</li>
</ol>
<p><strong>总结:</strong></p>
<p>使用 Stream API 可以使代码更加简洁易读,并且提高了代码的可维护性。通过使用 Stream API,我们可以轻松地对集合进行操作,并获得我们想要的结果。</p>
原文地址: https://www.cveoy.top/t/topic/o0Qr 著作权归作者所有。请勿转载和采集!