Java arraylist find all

Find element in ArrayList using indexOf lastIndexOf methods example

Find an element in ArrayList using indexOf lastIndexOf methods example shows how to find element in ArrayList using indexOf and lastIndexOf methods in Java. It also shows how to find an object of a custom class in ArrayList by implementing equals and hashCode methods.

How to find an element in ArrayList using the indexOf lastIndexOf methods in Java?

The ArrayList indexOf method returns the index of an element in the ArrayList object.

This method returns the index of the first occurrence of the specified object in the ArrayList. If the specified object is not found, the indexOf method returns -1.

Similarly, use the lastIndexOf method of the ArrayList class to find an element’s last index.

This method returns the index of the last occurrence of the specified object in the ArrayList. If the specified object is not found in the ArrayList, this method returns -1.

Читайте также:  Css rounding one corner

How to find element index in ArrayList of custom class objects?

Consider below given example which uses an ArrayList of custom class objects.

Even if the object was in the ArrayList, the indexOf method could not find it and returned -1. That is because the indexOf and lastIndexOf methods rely on the equals method to compare the objects and since we have not implemented the equals method in the Customer class, it could not find it.

Here is the updated version of Customer class which implements equals and hashCode methods.

Источник

ArrayList: Find all Indexes of an Occurrence

send pies

posted 9 years ago

  • Report post to moderator
  • I am trying to read a list of people and show at what indexes that person appears. Below is what I have so far (I know it’s wrong), but I wondering what I can do make this do what I want. I reading on Array Lists right now, so I think toArray() is what I’m looking for, but I’m not sure.

    author & internet detective

    send pies

    posted 9 years ago

  • Report post to moderator
  • Sam,
    I don’t think you’ll be better off with an array than an ArrayList to find all occurrences. I can’t think of a better way than looping through the ArrayList and checking each value.

    Bartender

    send pies

    posted 9 years ago

  • Report post to moderator
  • Sam Pauken wrote: I am trying to read a list of people and show at what indexes that person appears. Below is what I have so far (I know it’s wrong), but I wondering what I can do make this do what I want. I reading on Array Lists right now, so I think toArray() is what I’m looking for, but I’m not sure.

    I’ll put you out of your misery: No it isn’t.

    Think about what you’re trying to do, and write it down on paper BEFORE you start coding.

    So — First question: What ARE you trying to do? (Hint: you’ve already written it in your post)

    Forget Java for a moment. What if you handed your list — let’s say a bunch of numbered cards with people’s names written on them — to a 10-year old kid and asked him to find a particular person, what would you expect HIM to do? Now, write that procedure down in detail and in English (or your native language) before you write one line of Java code.

    There’s no great mystery about programming once you understand the problem; but solutions will not just magically appear because you start coding. In fact, they’re far less likely to appear if you start coding without thinking first.

    Second question: Have you ever used ArrayList before? If not, you should probably read the tutorials before you go any further. If you have (and once you’ve completed the task above), make sure you have a copy of the API docs for java.util.ArrayList (←click) open on your desktop when you start coding.

    (BIG Hint: Once you HAVE read the API docs, you’ll probably discover that you can do what you want in 1 line of code — well, maybe a few more to get ALL indexes )

    «Leadership is nature’s way of removing morons from the productive flow» — Dogbert
    Articles by Winston can be found here

    Источник

    Как найти элемент в списке с помощью Java

    Поиск элемента в списке-очень распространенная задача, с которой мы сталкиваемся как разработчики.

    В этом кратком руководстве мы рассмотрим различные способы, которыми мы можем сделать это с помощью Java.

    Дальнейшее чтение:

    Проверка Сортировки списка в Java

    Инициализация списка Java в одной строке

    2. Настройка

    Сначала давайте начнем с определения Customer POJO:

    List customers = new ArrayList<>(); customers.add(new Customer(1, "Jack")); customers.add(new Customer(2, "James")); customers.add(new Customer(3, "Kelly")); 

    Обратите внимание, что мы переопределили hashCode и equals в нашем классе Customer .

    Исходя из нашей текущей реализации equals , два Customer объекта с одинаковым id будут считаться равными.

    Мы будем использовать этот список клиентов по пути.

    3. Использование Java API

    Сама Java предоставляет несколько способов поиска элемента в списке:

    3.1. содержит()

    List предоставляет метод с именем содержит :

    boolean contains(Object element)

    Как следует из названия, этот метод возвращает true , если список содержит указанный элемент, и возвращает false в противном случае.

    Поэтому, когда нам нужно проверить, существует ли конкретный элемент в нашем списке, мы можем:

    Customer james = new Customer(2, "James"); if (customers.contains(james)) < // . >

    3.2. Индекс()

    indexOf – еще один полезный метод поиска элементов:

    int indexOf(Object element)

    Этот метод возвращает индекс первого вхождения указанного элемента в данный список или -1, если список не содержит элемента .

    Таким образом, логически, если этот метод возвращает что-либо, кроме -1, мы знаем, что список содержит элемент:

    if(customers.indexOf(james) != -1) < // . >

    Главное преимущество использования этого метода заключается в том, что он может сообщить нам положение указанного элемента в данном списке.

    3.3. Основные циклы

    А что, если мы хотим выполнить поиск элемента на основе полей? Например, скажем, мы объявляем лотерею, и нам нужно объявить Клиента с определенным именем победителем.

    Для таких полевых поисков мы можем обратиться к итерации.

    Традиционный способ итерации по списку-использовать одну из циклических конструкций Java. На каждой итерации мы сравниваем текущий элемент в списке с элементом, который мы ищем, чтобы увидеть, соответствует ли он:

    public Customer findUsingEnhancedForLoop( String name, List customers) < for (Customer customer : customers) < if (customer.getName().equals(name)) < return customer; >> return null; >

    Здесь имя относится к имени, которое мы ищем в данном списке клиентов . Этот метод возвращает первый Customer объект в списке с соответствующим именем или null , если такого Customer не существует.

    3.4. Цикл С итератором

    Итератор – это еще один способ обхода списка элементов.

    Мы можем просто взять наш предыдущий пример и немного подправить его:

    public Customer findUsingIterator( String name, List customers) < Iteratoriterator = customers.iterator(); while (iterator.hasNext()) < Customer customer = iterator.next(); if (customer.getName().equals(name)) < return customer; >> return null; >

    Следовательно, поведение остается таким же, как и раньше.

    3.5. Java 8 Stream API

    Начиная с Java 8, мы также можем использовать Stream API для поиска элемента в списке .

    Чтобы найти элемент, соответствующий определенным критериям в данном списке, мы:

    • вызовите stream() в списке
    • вызовите метод filter() с соответствующим предикатом
    • вызовите конструкцию find Any () , которая возвращает первый элемент, соответствующий предикатуfilter, завернутому вOptional , если такой элемент существует
    Customer james = customers.stream() .filter(customer -> "James".equals(customer.getName())) .findAny() .orElse(null);

    Для удобства мы по умолчанию используем значение null в случае, если Необязательный пуст, но это не всегда может быть лучшим выбором для каждого сценария.

    4. Сторонние Библиотеки

    Теперь, хотя Stream API более чем достаточен, что нам делать, если мы застряли на более ранней версии Java?

    К счастью, есть много сторонних библиотек, таких как Google Guava и Apache Commons, которые мы можем использовать.

    4.1. Google Guava

    Google Guava предоставляет функциональность, похожую на то, что мы можем сделать с потоками:

    Customer james = Iterables.tryFind(customers, new Predicate() < public boolean apply(Customer customer) < return "James".equals(customer.getName()); >>).orNull();

    Как и в случае с Stream API, мы можем дополнительно выбрать возврат значения по умолчанию вместо null :

    Customer james = Iterables.tryFind(customers, new Predicate() < public boolean apply(Customer customer) < return "James".equals(customer.getName()); >>).or(customers.get(0));

    Приведенный выше код выберет первый элемент в списке, если совпадение не будет найдено.

    Кроме того, не забывайте, что Гуава бросает Исключение NullPointerException если либо список, либо предикат нулевой .

    4.2. Apache Commons

    Мы можем найти элемент почти точно таким же образом, используя Apache Commons:

    Customer james = IterableUtils.find(customers, new Predicate() < public boolean evaluate(Customer customer) < return "James".equals(customer.getName()); >>);

    Однако есть несколько важных отличий:

    1. Apache Commons просто возвращает null , если мы передаем список null .
    2. Ононе обеспечивает функциональность значений по умолчанию, как у Guavaпопробуй Найти.

    5. Заключение

    В этой статье мы изучили различные способы поиска элемента в списке , начиная с быстрых проверок существования и заканчивая полевыми поисками.

    Мы также рассмотрели сторонние библиотеки Google Guava и Apache Commons как альтернативы Java 8 Streams API.

    Спасибо, что заглянули, и не забудьте проверить все источники для этих примеров на GitHub.

    Читайте ещё по теме:

    Источник

    Class ArrayList

    Type Parameters: E — the type of elements in this list All Implemented Interfaces: Serializable , Cloneable , Iterable , Collection , List , RandomAccess Direct Known Subclasses: AttributeList , RoleList , RoleUnresolvedList

    Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null . In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector , except that it is unsynchronized.)

    The size , isEmpty , get , set , iterator , and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

    Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.

    An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.

    Note that this implementation is not synchronized. If multiple threads access an ArrayList instance concurrently, and at least one of the threads modifies the list structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the list. If no such object exists, the list should be «wrapped» using the Collections.synchronizedList method. This is best done at creation time, to prevent accidental unsynchronized access to the list:

    List list = Collections.synchronizedList(new ArrayList(. ));

    The iterators returned by this class’s iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove or add methods, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

    Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

    This class is a member of the Java Collections Framework.

    Источник

    Оцените статью