简体   繁体   中英

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++;

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"

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM