java - 如何在ArrayList java中查找所有带有字符串索引的事件

有一个包含如下数据的 ArrayList。我的要求是找到数据长度为 4 的所有索引。


values.add("1000");

values.add("10001111");

values.add("45678901");

values.add("1111");

values.add("22222222");

values.add("2222");

values.add("33333333");


慕慕森
浏览 227回答 3
3回答

慕尼黑5688855

你需要 :迭代值检查长度如果条件通过,则保留索引Workable demo&nbsp;:使用Streams您可以内联解决方案以获得一个List或一个int[]List<Integer> indexes = values.stream().filter(s -> s.length() == 4)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(values::indexOf)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toList());int[] indexesArray = values.stream().filter(s -> s.length() == 4)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .mapToInt(values::indexOf)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .toArray();Workable demo&nbsp;:使用经典for loopList<Integer> indexes = new ArrayList<>();for(int i=0; i<values.size(); i++){&nbsp; &nbsp; if(values.get(i).length() == 4){&nbsp; &nbsp; &nbsp; &nbsp; indexes.add(i);&nbsp; &nbsp; }}

catspeake

您可以创建一个IntStream索引:IntStream&nbsp;allIndices&nbsp;=&nbsp;IntStream.range(0,&nbsp;values.size());然后您可以根据您提供的条件进行过滤:IntStream&nbsp;filteredIndices&nbsp;=&nbsp;allIndices.filter(i&nbsp;->&nbsp;values.get(i).length()&nbsp;==&nbsp;4);最后,您可以将这些索引转换为您喜欢的任何数据结构。数组:int[]&nbsp;indices&nbsp;=&nbsp;filteredIndices.toArray();或者一个列表List<Integer>&nbsp;indices&nbsp;=&nbsp;filteredIndices.boxed().collect(Collectors.toList());作为一个声明:int[]&nbsp;indices&nbsp;=&nbsp;IntStream.range(0,&nbsp;values.size()) &nbsp;&nbsp;&nbsp;&nbsp;.filter(i&nbsp;->&nbsp;values.get(i).length()&nbsp;==&nbsp;4) &nbsp;&nbsp;&nbsp;&nbsp;.toArray();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java