简体   繁体   中英

Java - searching string in ArrayList of objects

I got my class with constructor:

public Dane(String Imie, String Nazwisko, String nrTelefonu, int licznik)
 {
    this.id.Imie = Imie;
    this.id.Nazwisko = Nazwisko;
    this.id.nrTelefonu = nrTelefonu;
    this.id.licznik = licznik;

}

and a ArrayList of those objects...

 static List<Dane> listaOsob = new ArrayList<Dane>();

at this moment I am searching using something like this:

for(int i=0;i<listaOsob.size();i++)
                    {
                        if ((listaOsob.get(i).id.Imie).equals("Krzysiek"))
                            {
                                listaOsob.get(i).opis();
                            }
                    }

So... I know how to search when someone gives me full name, last name or telephone number... but I would like it to search always like this:

Type text to search: Krz

so It would find Krzysztof Marecki 700700700 Krzysiek Fraczak 500500500'

etc etc

How can I do this?

    Dane d = listaOsob.get(i)
    if(d.id.Imie.contains(searchTxt) || d.id.Nazwisko.contains(searchTxt) ||
        nrTelefonu.contains(searchTxt)|| licznik.toSring().contains(searchTxt)){
        listaOsob.get(i).opis();
    }

Or you can write a toString method for your Dane class and than test it like this:

Dane d = listaOsob.get(i)
d.toString().contains(searchTxt)

I'd choose the new functional notation of Java 8, it's simpler, more elegant, and is the trend to future of the language.

//if you want just the first result of that search

Dave dave = listaOsob.stream().filter((d) -> d.getId().getImie().equals("textSearch")).findFirst().get();

//if you want a list of results of that search

Collection<Dave> daves = listaOsob.stream().filter((d) -> d.getId().getImie().equals("textSearch")).collect(Collectors.toList());

//if you want just to know if it exists

boolean matchedResult = listaOsob.stream().anyMatch((d) -> d.getId().getImie().equals("textSearch"));

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