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
CodePudding user response:
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"
.
CodePudding user response:
You should not worry about the size of numbers
list, just add appropriate indexes as needed:
public static List<Integer> getIntegerArray(List<String> words, String word) {
List<Integer> numbers = new ArrayList<>();
for (int i = 0, n = words.size(); i < n; i ) {
if (Objects.equals(word, words.get(i)))
numbers.add(i);
}
return numbers;
}
Or use Stream API to get the list of indexes:
public static List<Integer> getIntegerArray(List<String> words, String word) {
return IntStream.range(0, words.size())
.filter(i -> Objects.equals(word, words.get(i)))
.boxed()
.collect(Collectors.toList());
}