How to Search in a List of Java Object

How to search in a List of Java object

You can give a try to Apache Commons Collections.

There is a class CollectionUtils that allows you to select or filter items by custom Predicate.

Your code would be like this:

Predicate condition = new Predicate() {
boolean evaluate(Object sample) {
return ((Sample)sample).value3.equals("three");
}
};
List result = CollectionUtils.select( list, condition );

Update:

In java8, using Lambdas and StreamAPI this should be:

List<Sample> result = list.stream()
.filter(item -> item.value3.equals("three"))
.collect(Collectors.toList());

much nicer!

Fastest way to search for an object in a list in java

As @ShreyasSarvothama says in the comments, the fastest way to retrieve values would be using a Map.

I think you could use a map whose keys are calculated with the values you use as parameters of your find method (taking into account that the combination of them gives a unique identifier of a DataItem).

import java.util.*;
import java.util.stream.*;

public class Test {

private class DataItem {
public int wordID, categoryID, documentID, count;

public DataItem(int w, int c, int d) {
wordID = w;
categoryID = c;
documentID = d;
}

public String toString() {
return "wordID:" + wordID + " categoryID:" + categoryID + " documentID:" + documentID;
}
}

private Map<Integer, DataItem> map;

public void setList(List<DataItem> list) {
this.map = list.stream().collect(Collectors.toMap(dataItem -> dataItem.wordID * dataItem.categoryID * dataItem.documentID, dataItem -> dataItem));
}

public DataItem getDataItem(int wordID, int categoryID, int documentID) {
return map.get(wordID * categoryID * documentID);
}

public static void main(String[] args) {
Test t = new Test();
t.setList(Arrays.asList(t.new DataItem(1,2,3), t.new DataItem(2,3,4), t.new DataItem(3,3,4)));
System.out.println(t.getDataItem(2,3,4));
}
}

Hope it helps.

Java, searching within a list of objects?

If you just as a one-off operation need to find the object(s) whose getName() is a particular value, then there's probably not much magic possible: cycle through the list, call getName() on each object, and for those that match, add them to your list of results.

If getName() is an expensive operation and there's some other way of a-priori working out if a given object definitely won't return a matching value, then obviously you can build in this 'filtering' as you cycle through.

If you frequently need to fetch objects for a given getName(), then keep an index (e.g. in a HashMap) of [result of getName()->object -> list of matches]. You'll need to decide how and if you need to keep this "index" in synch with the actual list.

See also the other proposition to use binarySearch() but to keep the list maintained. This way, inserts are more expensive than with a map and unsorted list, but if inserts are infrequent compared to lookups, then it has the advantage of only needing to maintain one structure.

Search for field in a List of Objects in Java

Check the method indexOf of the Collections API, it's what you're looking for.

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.

Below is the code for it.

import java.util.ArrayList;

public class HelloWorld{

public static void main(String []args){
String author_name = "abc";
ArrayList<book> bk = new ArrayList<book>();
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<book> booksByAuthor = new ArrayList<book>();
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.

Java List.contains(Object with field value equal to x)

Streams

If you are using Java 8, perhaps you could try something like this:

public boolean containsName(final List<MyObject> list, final String name){
return list.stream().filter(o -> o.getName().equals(name)).findFirst().isPresent();
}

Or alternatively, you could try something like this:

public boolean containsName(final List<MyObject> list, final String name){
return list.stream().map(MyObject::getName).filter(name::equals).findFirst().isPresent();
}

This method will return true if the List<MyObject> contains a MyObject with the name name. If you want to perform an operation on each of the MyObjects that getName().equals(name), then you could try something like this:

public void perform(final List<MyObject> list, final String name){
list.stream().filter(o -> o.getName().equals(name)).forEach(
o -> {
//...
}
);
}

Where o represents a MyObject instance.

Alternatively, as the comments suggest (Thanks MK10), you could use the Stream#anyMatch method:

public boolean containsName(final List<MyObject> list, final String name){
return list.stream().anyMatch(o -> name.equals(o.getName()));
}

How to search for an Object in ArrayList?

created the list and the search item:

List<String> list = new ArrayList<String>();
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<String> 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 :)

How can i search in a custom object type array list ? whats is best and fastest way

You could try something like this:

package com.company;

import java.util.ArrayList;
import java.util.List;

public class Test {
private String val;

public Test(String s) {
this.val = s;
}

public static void main(String[] args) {
List<Test> values = new ArrayList<>();
values.add(new Test("one"));
values.add(new Test("two"));
values.add(new Test("three"));

System.out.println(listContains(values, "two"));
System.out.println(listContains(values, "five"));
}

public static boolean listContains(List<Test> customTypeList, String searchedString) {
return customTypeList.stream().anyMatch((v) -> v.val.contains(searchedString));
}
}

If you're searching for fastest solution and searched strings are exactly the values from objects in your list (not interested in substrings), then you may want to map strings from your objects to these object's references like this:

        (...)
List<Test> values = new ArrayList<>();
values.add(new Test("one"));
values.add(new Test("two"));
values.add(new Test("three"));

Map<String, Test> indices = new HashMap<>();
for (Test v : values) {
indices.put(v.val, v);
}

System.out.println(indices.containsKey("two"));
System.out.println(indices.containsKey("five"));
// or...
System.out.println(indices.keySet().contains("two"));
System.out.println(indices.keySet().contains("five"));
(...)

IMPORTANT: You would need to update your indices whenever you change the content of your list though. Note that in this case string values inside objects must be valid keys for these objects (unique values). Example:

    public static void main(String[] args) {
List<Test> values = new ArrayList<>();
Map<String, Test> indices = new HashMap<>();

addToList(values, indices, new Test("one"));
addToList(values, indices, new Test("two"));
addToList(values, indices, new Test("three"));

System.out.println(indices.keySet().contains("two"));
System.out.println(indices.keySet().contains("five"));

removeFromList(values, indices, "two");

System.out.println(indices.keySet().contains("two"));
}

private static void addToList(List<Test> values, Map<String, Test> indices, Test item) {
values.add(item);
indices.put(item.val, item);
}

private static void removeFromList(List<Test> values, Map<String, Test> indices, String key) {
Test item = indices.remove(key);
values.remove(item);
}

Finding object in list by specific criteria

Implement Comparable rather than Comparator.

Make your compareTo function so it sorts the students in desired order (reversed)

Sort your stream, skip 1 entry, return the next one.

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

public class Student implements Comparable<Student> {
private String firstName;
private String lastName;
private LocalDate dateOfBirth;
private double averageMark;

public Student(String firstName, String lastName, LocalDate dateOfBirth, double averageMark) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.averageMark = averageMark;
}

public double getAverageMark() {
return averageMark;
}

//function below must find student that I described upper. Currently
//function is incomplete because I still try to find correct solution
public static Student findSecondBestStudent(List<Student> students) {
return students.stream().sorted().skip(1).findFirst().orElse(null);
}

@Override
public int compareTo(Student other) {
if (other == null)
return 1;
if (other.averageMark == averageMark) {
if (other.dateOfBirth == null)
return -1;
return other.dateOfBirth.compareTo(dateOfBirth);
}
return Double.compare(other.averageMark, averageMark);
}

@Override
public String toString() {
return "Student [firstName=" + firstName + ", lastName=" + lastName + ", dateOfBirth=" + dateOfBirth
+ ", averageMark=" + averageMark + "]";
}

public static void main(String[] args) {
final List<Student> students = new ArrayList<>(6);
students.add(new Student("Peter", "Tibbitts", LocalDate.of(2001, 4, 6), 5));
students.add(new Student("Leon", "Gaston", LocalDate.of(1951, 6, 17), 12));
students.add(new Student("Eric", "Carter", LocalDate.of(1945, 12, 24), 9));
students.add(new Student("Richard", "Heard", LocalDate.of(1984, 5, 9), 4));
students.add(new Student("Frankie", "Bonner", LocalDate.of(1970, 4, 19), 10));
students.add(new Student("Donald", "Pascal", LocalDate.of(2000, 3, 26), 10));

final Student result = Student.findSecondBestStudent(students);
System.out.println(result);
}

}

Java search list of objects for variable

Add a method hasAuthor(String) to your Book which loops through the List<Author> list and compares the name. Like so:

boolean hasAuthor(String name) {
for (Author author : authors) {
if (author.name.equals(name)) {
return true;
}
}
return false;
}

To find books with a specific author, you loop over the List<Book> and invoke the hasAuthor(String) method.



Related Topics



Leave a reply



Submit