Java find in list by property

How to Find an Object in an Arraylist by Property

Searching in a ArrayList with custom objects for certain strings

The easy way is to make a for where you verify if the atrrtibute name of the custom object have the desired string

 for(Datapoint d : dataPointList) if(d.getName() != null && d.getName().contains(search)) 
//something here
>

How to search for an Object in ArrayList?

created the list and the search item:

List list = new ArrayList(); 
list.add("book");
list.add("pencil");
list.add("note");

String itemToBeSearched = "book"; // taken as example

if(check(list,itemToBeSearched)) System.out.println("ITEM FOUND");
>
else
System.out.println("NOT FOUND");
>

then the item check function is

public static boolean check(List list, String itemToBeSearched) boolean isItemFound =false; 
for(String singleItem: list) if(singleItem.equalsIgnoreCase(itemToBeSearched)) isItemFound = true;
return isItemFound;
>
>
return isItemFound;
>

and it’s working for me, please try this and let us know 🙂

Search for a particular element from object in ArrayList

Using for loop over ArrayList can solve your problem, it’s naive method and old fashioned.

import java.util.ArrayList;

public class HelloWorld
public static void main(String []args) String author_name = "abc";
ArrayList bk = new ArrayList();
bk.add(new book("abc", "abc", "abc", 10));
bk.add(new book("mno", "mno", "abc", 10));
bk.add(new book("xyz", "abc", "abc", 10));
ArrayList booksByAuthor = new ArrayList();
for(book obj : bk)
if(obj.author_nm == author_name)
booksByAuthor.add(obj);
>
>

>
>

class book public String book_nm;
public String author_nm;
public String publication;
public int price;
public book(String book_nm,String author_nm,String publication,int price) this.book_nm=book_nm;
this.author_nm=author_nm;
this.publication=publication;
this.price=price;
>
>

Hope you can get an idea from it.

Источник

How to find an object in an ArrayList by property

Solution 1: In Java8 you can use streams: Additionally, in case you have many different objects (not only ) or you want to find it by different properties (not only by ), you could build an utility class, to ecapsulate this logic in it: Solution 2: You can’t without an iteration. that means I need to get School object not school name.

Читайте также:  Java всплывающее окно при наведении

How to find an object in an ArrayList by property

How can I find an object, Carnet , in a ArrayList knowing its property codeIsin .

List listCarnet = carnetEJB.findAll(); public class Carnet < private String codeTitre; private String nomTitre; private String codeIsin; // Setters and getters >

In Java8 you can use streams:

public static Carnet findByCodeIsIn(Collection listCarnet, String codeIsIn) < return listCarnet.stream().filter(carnet ->codeIsIn.equals(carnet.getCodeIsin())).findFirst().orElse(null); > 

Additionally, in case you have many different objects (not only Carnet ) or you want to find it by different properties (not only by cideIsin ), you could build an utility class, to ecapsulate this logic in it:

public final class FindUtils < public static T findByProperty(Collection col, Predicate filter) < return col.stream().filter(filter).findFirst().orElse(null); >> public final class CarnetUtils < public static Carnet findByCodeTitre(CollectionlistCarnet, String codeTitre) < return FindUtils.findByProperty(listCarnet, carnet ->codeTitre.equals(carnet.getCodeTitre())); > public static Carnet findByNomTitre(Collection listCarnet, String nomTitre) < return FindUtils.findByProperty(listCarnet, carnet ->nomTitre.equals(carnet.getNomTitre())); > public static Carnet findByCodeIsIn(Collection listCarnet, String codeIsin) < return FindUtils.findByProperty(listCarnet, carnet ->codeIsin.equals(carnet.getCodeIsin())); > > 

You can’t without an iteration.

Carnet findCarnet(String codeIsIn) < for(Carnet carnet : listCarnet) < if(carnet.getCodeIsIn().equals(codeIsIn)) < return carnet; >> return null; > 

Override the equals() method of Carnet .

Storing your List as a Map instead, using codeIsIn as the key:

HashMap carnets = new HashMap<>(); // setting map Carnet carnet = carnets.get(codeIsIn); 

If you use Java 8 and if it is possible that your search returns null, you could try using the Optional class.

private final Optional findCarnet(Collection yourList, String codeIsin) < // This stream will simply return any carnet that matches the filter. It will be wrapped in a Optional object. // If no carnets are matched, an "Optional.empty" item will be returned return yourList.stream().filter(c ->c.getCodeIsin().equals(codeIsin)).findAny(); > 
public void yourMethod(String codeIsin) < ListlistCarnet = carnetEJB.findAll(); Optional carnetFound = findCarnet(listCarnet, codeIsin); if(carnetFound.isPresent()) < // You use this ".get()" method to actually get your carnet from the Optional object doSomething(carnetFound.get()); >else < doSomethingElse(); >> 

Here, We can use a function like this:

To find all the objects with a specific codeIsIn:

 public static List findBycodeIsin(Collection listCarnet, String codeIsIn) < return items.stream().filter(item ->codeIsIn.equals(item.getCodeIsIn())) .collect(Collectors.toList()); > 

To find a Single item (If the codeIsIn is unique for each object):

public static Carnet findByCodeIsIn(Collection listCarnet, String codeIsIn) < return listCarnet.stream().filter(carnet->codeIsIn.equals(carnet.getCodeIsIn())) .findFirst().orElse(null); > 

How to use the ArrayList.contain() to check the object in, Yes, contains () internally use equals method to check two object are equals or not when compare your given object with existing list object. So if your …

Читайте также:  Nfc android studio kotlin

Find object in ArrayList

I want to find a LegalEntity object in an ArrayList . The object can possibly be a different instance. I’m only interested in whether they represent the same value, i.e. they have the same primary key. All LegalEntity instances are created from database values by EJB:

List allLegalEntities = myEJB.getLegalEntityfindAll()); LegalEntity currentLegalEntity = myEJB.getLegalEntityfindById(123L); 

My first naive idea never finds matches:

if (allLegalEntities.contains(currentLegalEntity))

I then thought that perhaps I need to create my own equals() method:

public boolean equals(LegalEntity other)

But this method is not even being invoked. Is there a way to find an object in a list that doesn’t involve looping?

I’m learning Java so it might easily be some foolish misunderstanding on my side.

Your approach is correct, but you need to override the method equals that accepts an Object :

@Override public boolean equals(Object obj) < if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LegalEntity other = (LegalEntity) obj; // check if equals based one some properties >

However you also need to override hashCode :

@Override public int hashCode() < // return a unique int >

So this might not be the easiest solution.

Another approach is to use filter :

LegalEntity myLegalEntity = myEJB.getLegalEntityfindAll().stream() .filter(legalEntity -> legalEntity.getProperty().equals("someting")) .findAny() .orElse(null); 

If you’re using Java 8 you can use streams:

List allLegalEntities = myEJB.getLegalEntityfindAll()); LegalEntity currentLegalEntity = allLegalEntities.stream().filter(entity -> entity.getId() == 123L).findFirst(); 

Java — Find same object in two arraylist, Find same object in two arraylist [duplicate] Ask Question Asked 3 months ago. Modified 3 months ago. Viewed 52 times 0 This question When …

Find specific object in an arraylist

Currently have an issue getting a specific object in an arraylist. So I have multiple classes that implements the same interface, and I create objects of the different classes. The problem is that I don’t know how to differentiate the classes in the arraylist.

ArrayList arraylist = new ArrayList<>(); public static void main(String[] args) < addInterface(new interfaceA()); addInterface(new interfaceB()); addInterface(new interfaceC()); >public static void addInterface(Interface foo)

Let say that I want to get interfaceA() , I could call it by arraylist.get(0) but I don’t want to hardcode it. Each class has the same methods but the code is different.

Читайте также:  Css templates one page template

I would use a Map instead of a List . In this case an IdentityHashMap is a good fit.

interface Thing < >IdentityHashMap, Thing> things = new IdentityHashMap<>(); class ThingA implements Thing < @Override public String toString() < return "ThingA<>"; > > class ThingB implements Thing < @Override public String toString() < return "ThingB<>"; > > class ThingC implements Thing < @Override public String toString() < return "ThingC<>"; > > public void registerThing(Thing thing) < things.put(thing.getClass(), thing); >public void test(String[] args)

You could filter using a predicate, by checking runtime classes:

List interfaceAList = arraylist.stream() .filter(e -> InterfaceA.class.isInstance(e)) .collect(Collectors.toList()); 
 public Interface getInterfaceA(List interfaces) < for (Interface i : interfaces) < if (i instanceof InterfaceA) return i; >return null; > 

Find a String in ArrayList of objects, Find a String in ArrayList of objects — java. Ask Question Asked 4 years, 6 months ago. Modified 4 years, 6 months ago. Viewed 732 times 1 I …

Get a specific object in arrayList

How can I get a List data in School list ?

List schools = new ArrayList(); School school_aaa = new School(); school_aaa.setName( "aaa" ); Student student_aaa_001 = new Student(); student_aaa_001.setName( "aaa_001" ); student_aaa_001.setAge( 17 ); student_aaa_001.setId( 21345678 ); Student student_aaa_002 = new Student(); student_aaa_002.setName( "aaa_002" ); student_aaa_002.setAge( 13 ); student_aaa_002.setId( 6789876 ); List students = new ArrayList(); students.add( student_aaa_001 ); students.add( student_aaa_002 ); school_aaa.setStudents( students ); schools.add("aaa"); 

I only have school name. But it couldn’t use indexOf method. because that’s only works same object.

that means I need to get School object not school name.

how do I find School object.

Student.java

School.java

It seems like you are trying to find a specific school in the list of schools. If this is not what you are trying to do, please let me know.

public School findSchool(String schoolName) < // Goes through the List of schools. for (School i : schools) < if (i.getName.equals(schoolname)) < return i; >> return null; > 

Java 8’s streaming API gives you a pretty neat syntax to doing so, by filtering. If you can assume that there’s only one school with a given name, you could use the findFirst() method:

School aaaSchool = schools.stream() .filter(x -> x.getName().equals("aaa")) .findFirst() .orElse(null); 

If you can’t, you’ll have to do with a sub-list of schools:

List aaaSchools = schools.stream() .filter(x -> x.getName().equals("aaa")) .collect(Collectors.toList()); 

Java — get a specific object in arrayList, how do I find School object. here are DataTypes. Student.java School.java java android arraylist. Share. Improve this question. Follow edited …

Источник

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