How to create an element search method in an Arraylist?

Asked

Viewed 1,141 times

-2

Assuming an Arraylist that stores objects, and these objects have attributes of various types (int, String , float, etc...). Knowing this I want to create a method to find an object in Arraylist through a keyword or number that can be inside an element of the Array or not. Other than by the index of each element.

  • Be more specific about what you are trying to do. Give an example of the objects you have and the type of search you want to do.

3 answers

3


You can do something like:

public class Pessoa {

    private int id;
    private String nome;
    private int idade;

    public Pessoa(int id, String nome, int idade) {
        this.id = id;
        this.nome = nome;
        this.idade = idade;
    }

    public int getId() {
        return id;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getIdade() {
        return idade;
    }

    public void setIdade(int idade) {
        this.idade = idade;
    }
}

import java.util.ArrayList;

public class Main {

    public static void main(String[] args) {

        ArrayList<Pessoa> pessoas = new ArrayList<Pessoa>();

        pessoas.add(new Pessoa(1, "José", 32));
        pessoas.add(new Pessoa(2, "João", 25));
        pessoas.add(new Pessoa(3, "Maria", 43));

        Pessoa pessoaPeloNome = buscaPeloNome(pessoas, "João");
        Pessoa pessoaPelaIdade = buscaPelaIdade(pessoas, 43);

        if(pessoaPeloNome != null) {
            System.out.println("Pessoa pelo nome: " + pessoaPeloNome.getId() + " | " + pessoaPeloNome.getNome() + " | " + pessoaPeloNome.getIdade());
        }

        if(pessoaPelaIdade != null) {
            System.out.println("Pessoa pela idade: " + pessoaPelaIdade.getId() + " | " + pessoaPelaIdade.getNome() + " | " + pessoaPelaIdade.getIdade());
        }
    }

    public static Pessoa buscaPeloNome(ArrayList<Pessoa> pessoas, String nome) {

        for(Pessoa pessoa : pessoas) {
            if(pessoa.getNome().equals(nome)) {
                return pessoa;
            }
        }
        return null;
    }

    public static Pessoa buscaPelaIdade(ArrayList<Pessoa> pessoas, int idade) {

        for(Pessoa pessoa : pessoas) {
            if(pessoa.getIdade() == idade) {
                return pessoa;
            }
        }
        return null;
    }
}

Exit:

Person by name: 2 | John | 25
Person by age: 3 | Maria | 43

  • Your solution has helped me a lot, thank you very much.

  • @Legal Ogarov. He was happy to help. Could you mark the answer as a solution, please? It is the "check" sign under the number of votes of the reply.

  • Do you know how I can generate an id for each object I add to Arraylist ? Type an ID that cannot be changed and is forever of an object ?

  • 1

    There are several ways to do this, one of them is by creating a field of id in the class in question, receive this id by the constructor and do only the method getter not Setter. I’ll edit the post to include it. @Ogarov

  • @Ogarov edited response.

2

The easiest way is:

Arrays.asList("Débora", "Luan").stream().filter(string -> string.equals("Luan"))
    .collect(Collectors.reducing((a, b) -> null)).get();

Or even, what would be more protected in case there is no item that resembles the information given:

Arrays.asList("Débora", "Luan").stream().filter(parametroFiltro -> parametroFiltro.equals("Luan")).findFirst().get();

I used some tools available from version 1.8 of Java. With lambda expressions it is easier to write small functional classes with only one method, which takes a parameter (the Filter parameter), and defines it within a method (so the arrow, ->, is used to indicate how it will be executed).

For example, the method filter used after the stream is used to "filter" the collection from a given check.

The code .filter(parametroFiltro -> parametroFiltro.equals("valor") may be replaced by:

.filter(new Predicate<String>(){

    @Override
    public boolean test(String parametroFiltro) {
        return parametroFiltro.equals("Luan");
    }
})

In the case of filter, as it expects an instantiated object from the Predicate interface, it knows that it must execute the defined code is parametroFiltro -> parametroFiltro.equals("valor") as a method that has something like return and takes only a String type parameter.

The second use of lambda was used to define as a parameter reducing an instance of the Binaryoperator class, which has the method apply as a method that takes two variables and returns a type T, defined in the anonymity class creation. in this case:

Collectors.reducing(new BinaryOperator<String>() {

    @Override
    public String apply(String a, String b) {
        return null;
    }
}

There’s no charge on that, I told you because I thought it was cool to share more fun ways of dealing with it.

And anyway, please, if more studied people on the subject manage to complete the information I am immensely grateful.

  • Thanks for the help, I’m still beginners and there are some things in your code that I don’t understand.

  • 1

    @Ogarov, Oook, so you don’t understand I suppose it’s the Ambo expressions. I’ll explain it to you as best I can. Open for others to improve the explanation.

0

you create a class that implements an Arraylist and then you can implement a search method and overwrite it for each desired attribute. Collections already implement these standard methods. Sort: Sorts the elements of a List. binarySearch: Locates an object in a List using the introduced high-performance binary search algorithm. To use them the objects you place in Arraylist need to have the method compareTo is declared in the Comparable interface and is sometimes called natural comparison method. The call Sort can specify as a second argument a Comparator object, which determines an alternative order of the elements. Reference is Java - How to Program 10th ed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.