PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 19, 2022

[FIXED] How can I convert arraylist <String> to arraylist <integer>

 July 19, 2022     arraylist, integer, java, string     No comments   

Issue

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]

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
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing