Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert arraylist <String> to arraylist <integer> and check on which index is every word from string list

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading