Issue
i tried to write a code which convert array list to and return on which index is string given as parameter,
public class List {
public static void main(String[] List) {
List<String> words = new ArrayList<>();
words.addAll(Arrays.asList("house", "bike","dog","house","house"));
System.out.println(getIntegerArray(words,house));
public static List<Integer> getIntegerArray(List<String> words, String word) {
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numbers.size() ; i++) {
}
And my goal is that output is arraylist>Integer>: [ 0,3,4]
First of all i want to check how many words contains arraylist 'words' so i will use loop for, after i check all of the elements and know how many there are i want to convert into Intager array list and output index of String word
Solution
You can do it just by checking if the string passed to the method is contained in the list and adding the number to the List numbers
.
Here an example of the method getIntegerArray
:
public static List<Integer> getIntegerArray(List<String> words, String word) {
List<Integer> numbers = new ArrayList<>();
for (int i=0; i < words.size() ; i++) {
if (word.equals(words.get(i)))
numbers.add(i);
}
return numbers;
}
PS: in System.out.println(getIntegerArray(words, house));
you are passing a variable house
which is not declared. Probably you wanted to write "house"
.
Answered By - Nagamura
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.