如何获取字符串数组元素的索引?
我在String [] Strarray
中有以下数据
1、9、3、4、16、6、7、8、2、10、11、12、12、13、45
我想找到包含3
的元素的索引(例如:3 ,13)。即,我应该有3 = str [2]和13 = str [12],仅使用 java 8 features “ test”
I have the below data in a String[] strArray
1, 9, 3, 4, 16, 6, 7, 8, 2, 10, 11, 12, 13, 45
I want to find the index of those elements that contain 3
(e.g:3,13). i.e I should have 3=str[2] and 13=str[12] with just use Java 8 features like stream and etc. because I want after finding their index, to replace them with specific string for example "Test"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一种方法。使用三元运算符
(?:)
来决定是否应用test
或原始值替换当前字符串。打印
以将数组元素的地图返回到您可以这样做的找到的匹配项索引。这将处理具有不同索引的重复值。
键
的每个实例的列表。打印
以用地图中的值索引替换原始数组,请执行以下操作。
Here is one way. Use the ternary operator
(?:)
to decide if the current string should be replaced withTest
or the original value.prints
To return a map of array element to index for the found matches you can do it like so. This will handle duplicate values with different indices.
key
was found.prints
To replace the original array with the indices of its values in the map, do the following.
您可以将阵列的长度从i = 0迭代到i<长度。在循环中,将str [i]转换为字符串,并使用java string contains()方法检查该字符串是否包含“ 3”,如果是的话,您可以在Array str [i] =“ test”的位置替换
。可以使用Java流方法,地图做同样的事情。
在这种情况下,您可能需要使用.toArray而不是收集作为列表。
You can take the length of the array and iterate from i=0 to i<length. In the loop convert str[i] to a String and check if that string contains “3” using the Java String Contains() method, if so you can replace at that spot in the array str[i]=“Test”
Alternatively you can do the same thing using the Java Stream method, Map.
You may want to use .toArray rather than collect as a list in this case.