Skip to content
Advertisement

How can I convert arraylist to arraylist

My goal is to find on which specific index is String from ArrayList and add them to new ArrayList, So if house is [0] than i want to return new ArrayList with integer.

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++) {

        }

At the begging I have ArrayList like this Input :

["house", "bike","dog"]

And I want to get new ArrayList like this Output:

[0,1,2]

Advertisement

Answer

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".

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement