AsYouWereAPx
AsYouWereAPx

Reputation: 31

Find a String in ArrayList of objects - java

I wrote a program that consists of an ArrayList, which contains objects. Every object has a name. I want to find the index in ArrayList with the same name as i would input it with scanner. I tried the following code, but it doesnt work. q=0; while(!naziv.equals(racuni.get(q).getNaziv())) q++;

Upvotes: 1

Views: 850

Answers (2)

nagendra547
nagendra547

Reputation: 6302

Simple way to solve this problem in JAVA8 is by using Stream

If element is available in list, it prints the first index of element, else returns -1.

OptionalInt findFirst = IntStream.range(0, objects.size())
.filter(object-> objects.get(object).getName().equals(nextLine))
.findFirst();
System.out.println(findFirst.isPresent() ? findFirst.getAsInt() : -1);

Upvotes: 0

Greggz
Greggz

Reputation: 1799

First let's format your code clearly

String name = sc.next();
int q=0;
while(q < object.size() && !name.equals(object.get(q).getName())) {
  q++;
}

Second, you must verify that q also is below the ArrayList size, cause it wouldn't make sense if you tried to access a position bigger than your Array.

Here have a sample

    ArrayList<Animal> object = new ArrayList<Animal>();
    object.add(new Animal("duck"));
    object.add(new Animal("chicken"));
    Scanner sc = new Scanner(System.in);
    String name = sc.next();
    int q = 0;
    while (q < object.size() && !name.equals(object.get(q).getName())) {
        q++;
    }
    System.out.print(q);

// Prints 0 if you write "duck"

// Prints 1 if you write "chicken"

// Prints 2 if you write "NotInArrayList"

Upvotes: 2

Related Questions