java - Get indices of unique WebElements.getText() objects in an ArrayList
问题描述
I have an ArrayList<WebElements>
whose elements all have some pieces of text. I'd like to store the indices of those WebElements
, which contain unique pieces of text in a new ArrayList<Integer>
. E.g. if the texts are (a,b,c,a,b,d) then I'd need (1,2,3,6).
I tried getting the texts to ArrayList<String> piecesOfText
with one stream
, picking the uniques with another one into ArrayList<String> piecesOfTextUnique
, then looping through piecesOfTextUnique
and getting the indices of those pieces of text in piecesOfText
via indexOf()
ArrayList<WebElement> webElementsWithText=getWebElements();
ArrayList<String> piecesOfText= new ArrayList<>();
webElementsWithText.stream()
.map(WebElement::getText)
.forEach(piecesOfText::add);
ArrayList<String> piecesOfTextUnique = (ArrayList<String>) piecesOfText.stream()
.distinct()
.collect(Collectors.toList());
ArrayList<Integer> uniqueIndeces=new ArrayList<>();
for (int i=0;i< piecesOfTextUnique.size();i++) {
uniqueIndeces.add(piecesOfText.indexOf(piecesOfTextUnique.get(i)));
}
This one does the job, but can someone suggest a more concise/elegant solution?
解决方案
- 您可以使用
collect
方法而不是Collection#add
-ing inforEach
。 - 你不能假设
Collectors.toList
回报java.util.ArrayList
。它可能导致ClassCastException
. piecesOfTextUnique
(语义上)与 等价piecesOfText.distinct()
,因此piecesOfText
可以内联。- 最后一个 for 循环可以替换为
IntStream
.
所以,最终结果是:
ArrayList<WebElement> webElementsWithText = getWebElements();
List<String> piecesOfTextUnique = webElementsWithText.stream()
.map(WebElement::getText)
.distinct()
.collect(Collectors.toList());
ArrayList<Integer> uniqueIndeces = IntStream.range(0, piecesOfTextUnique.size())
.mapToObj(i -> piecesOfTextUnique.get(i))
.map(s -> piecesOfText.indexOf(s))
.collect(Collectors.toCollection(ArrayList::new));
推荐阅读
- mysql - 如何将数据从一列行复制到同一列但不同的行
- angular - 在生产中更改 Angular 应用程序中的服务器 IP
- json - JQ:从数字对象中选择键
- vba - 如何在 VBA 中过滤减去 XX 个工作日?
- wicket - Wicket 获取按钮组件文本
- c# - IClientProxy.SendAsync 字符串方法参数中还有哪些其他选项?
- .net - 如何将附件添加到具有 (PDF/A-3) 文件格式的 pdf 文件?
- node.js - 如何在 NodeJS、Express、Mongoose 应用程序中为 Model.findOne 的回调函数定义全局变量?
- php - 用数字和文本替换数组
- mongodb - 在 mongoDB 中查找特定字段的最新数据