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 piecesOfTextUniqueand 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?