Java arraylist get by object

How to get a value inside an ArrayList java

revision thanks all for the answers, I should probably add to the code a bit more. in the Car class, i have another method that is calculating the total cost including the tax.

class Car < public Car (String name, int price, int, tax, int year)< constructor. >public void computeCars () < int totalprice= price+tax; System.out.println (name + "\t" +totalprice+"\t"+year ); >> 
public static void processCar(ArrayList cars) < int totalAmount=0; for (int i=0; i> 

7 Answers 7

Assuming your Car class has a getter method for price, you can simply use

System.out.println (car.get(i).getPrice()); 

where i is the index of the element.

Car c = car.get(i); System.out.println (c.getPrice()); 

You also need to return totalprice from your function if you need to store it

public static void processCar(ArrayList cars) < int totalAmount=0; for (int i=0; i> 

And change the return type of your function

hi, thanks for the help, I tried that but it is saying it is expecting an int but found void. I am not sure how to get around that. Thanks again

You haven’t shown your Car type, but assuming you’d want the price of the first car, you could use:

public static void processCars(ArrayList cars)

Note that I’ve changed the name of the list from car to cars — this is a list of cars, not a single car. (I’ve changed the method name in a similar way.)

Читайте также:  Xml to cpp class

If you only want the method to process a single car, you should change the parameter to be of type Car :

public static void processCar(Car car) 

and then call it like this:

// In the main method processCar(cars.get(0)); 

If you do leave it as processing the whole list, it would be worth generalizing the parameter to List — it’s unlikely that you’ll really require that it’s an ArrayList .

Источник

How to find an object in an ArrayList by property

If I were you I will find the source code from where ever and get it’s equals and hashCode implemented. The only other alternative is to manually iterate over the Collection and check for member equality.

I would rather use a map instead of a list. If you often look for objects and performance is an issue, a sorted map might be better. Implementing and using equal for this purpose is ugly in my point of view.

For Java 8 you can get the stream from the ArrayList and apply filter(e->e.codeIsIn.equals(. )) to it.

8 Answers 8

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); 

You can overried equals() method which will make sure that when this particular field ONLY (codeIsin in this case) of one object equals to the same field in another object they consider equal. Then you can create an object with this field and the same value (same as in the object you are looking for) and search through the list as follows: listCarnet.get(listCarnet.indexOf(OBJECT YOU HAVE JUST CREATED)).

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(); >> 

To find an object in an ArrayList by the property, 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); > 
private User findUserByName(List userList, final String name) < OptionaluserOptional = FluentIterable.from(userList).firstMatch(new Predicate() < @Override public boolean apply(@Nullable User input) < return input.getName().equals(name); >>); return userOptional.isPresent() ? userOptional.get() : null; // return user if found otherwise return null if user name don't exist in user list > 

Here is another solution using Guava in Java 8 that returns the matched element if one exists in the list. If more than one elements are matched then the collector throws an IllegalArgumentException. A null is returned if there is no match.

Carnet carnet = listCarnet.stream() .filter(c -> c.getCodeIsin().equals(wantedCodeIsin)) .collect(MoreCollectors.toOptional()) .orElse(null); 

Following with Oleg answer, if you want to find ALL objects in a List filtered by a property, you could do something like:

//Search into a generic list ALL items with a generic property public final class SearchTools < public static List findByProperty(Collection col, Predicate filter) < ListfilteredList = (List) col.stream().filter(filter).collect(Collectors.toList()); return filteredList; > //Search in the list "listItems" ALL items of type "Item" with the specific property "iD_item=itemID" public static final class ItemTools < public static ListfindByItemID(Collection listItems, String itemID) < return SearchTools.findByProperty(listItems, item ->itemID.equals(item.getiD_Item())); > > > 

and similarly if you want to filter ALL items in a HashMap with a certain Property

//Search into a MAP ALL items with a given property public final class SearchTools < public static HashMap filterByProperty(HashMap completeMap, Predicate filter) < HashMapfilteredList = (HashMap) completeMap.entrySet().stream() .filter(filter) .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue())); return filteredList; > //Search into the MAP ALL items with specific properties public static final class ItemTools < public static HashMapfilterByParentID(HashMap mapItems, String parentID) < return SearchTools.filterByProperty(mapItems, mapItem ->parentID.equals(mapItem.getValue().getiD_Parent())); > public static HashMap filterBySciName(HashMap mapItems, String sciName) < return SearchTools.filterByProperty(mapItems, mapItem ->sciName.equals(mapItem.getValue().getSciName())); > > 

Источник

How to use ArrayList’s get() method

I’m new to java (& to OOP too) and I’m trying to understand about the class ArrayList but I don’t understand how to use the get(). I tried searching in net, but couldn’t find anything helpful.

6 Answers 6

Here is the official documentation of ArrayList.get().

Anyway it is very simple, for example

ArrayList list = new ArrayList(); list.add("1"); list.add("2"); list.add("3"); String str = (String) list.get(0); // here you get "1" in str 

To put it nice and simply, get(int index) returns the element at the specified index.

So say we had an ArrayList of String s:

List names = new ArrayList(); names.add("Arthur Dent"); names.add("Marvin"); names.add("Trillian"); names.add("Ford Prefect"); 

A visual representation of the array list

Which can be visualised as: Where 0, 1, 2, and 3 denote the indexes of the ArrayList .

Say we wanted to retrieve one of the names we would do the following: String name = names.get(1); Which returns the name at the index of 1.

Getting the element at index 1

So if we were to print out the name System.out.println(name); the output would be Marvin — Although he might not be too happy with us disturbing him.

You use List#get(int index) to get an object with the index index in the list. You use it like that:

List list = new ArrayList(); list.add(new ExampleClass()); list.add(new ExampleClass()); list.add(new ExampleClass()); ExampleClass exampleObj = list.get(2); // will get the 3rd element in the list (index 2); 

ArrayList get(int index) method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.

public Element get(int index) 

Example : In below example we are getting few elements of an arraylist by using get method.

package beginnersbook.com; import java.util.ArrayList; public class GetMethodExample < public static void main(String[] args) < ArrayListal = new ArrayList(); al.add("pen"); al.add("pencil"); al.add("ink"); al.add("notebook"); al.add("book"); al.add("books"); al.add("paper"); al.add("white board"); System.out.println("First element of the ArrayList: "+al.get(0)); System.out.println("Third element of the ArrayList: "+al.get(2)); System.out.println("Sixth element of the ArrayList: "+al.get(5)); System.out.println("Fourth element of the ArrayList: "+al.get(3)); > > 
First element of the ArrayList: pen Third element of the ArrayList: ink Sixth element of the ArrayList: books Fourth element of the ArrayList: notebook 

Источник

ArrayList Retrieve object by Id

I want to retrieve the particular Account object based on an Id parameter in many parts of my application. What would be best way of going about this ? I was thinking of extending ArrayList but I am sure there must be better way.

7 Answers 7

It sounds like what you really want to use is a Map , which allows you to retrieve values based on a key. If you stick to ArrayList , your only option is to iterate through the whole list and search for the object.

for(Account account : accountsList) < if(account.getId().equals(someId) < //found it! >> 

This sort of operation is O(1) in a Map , vs O(n) in a List .

I was thinking of extending ArrayList but I am sure there must be better way.

Generally speaking, this is poor design. Read Effective Java Item 16 for a better understanding as to why — or check out this article.

Java Solution:

Account account = accountList.stream().filter(a -> a.getId() == YOUR_ID).collect(Collectors.toList()).get(0); 

Kotlin Solution 1:

val index = accountList.indexOfFirst < it.id == YOUR_ID >val account = accountList[index] 

Kotlin Solution 2:

val account = accountList.first

A better way to do this would be to use a Map.

In your case, you could implement it in the following way

you can use the «get» method to retrieve the appropriate account object.

Assuming that it is an unordered list, you will need to iterate over the list and check each object.

There’s also the other for syntax:

for(Account a : accountList) 

You could put this loop into a helper method that takes an Account and compares it against each item.

For ordered lists, you have more efficient search options, but you will need to implement a search no matter what.

You must use the Map for example:

private Map AccountMap; for (String account : accounts ) AccountMap.put(account, numberofid); 

ArrayList does not sort the elements contained. If you want to look for a single element in an ArrayList, you’re going to need to loop through the list and compare each one to the value you’re looking for.

Account foundAccount; for(Account a : accountList) < if(a.Id == targetID)< foundAccount = a; break; >> if(foundAccount != null) < //handle foundAccount >else < //not found >

Alternatively, you can use a more intelligent data structure which does sort and keep information on the data contianed.

You’ll want to research the Map interface, specifically the HashMap implementation. This lets you store each element in an order tied to a certain key. So you could place each of your objects in a HashMap with the Id as the key, and then you can directly ask the HashMap if it has an object of a certain key or not.

Источник

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