Jessica Chambers
Jessica Chambers

Reputation: 1316

Get an element from and Arraylist according to an attribute - Java

I have an Arraylist of a class "Variable". Each "Variable" object has a name (String) and a value (int). Is there an efficient way to retrieve the object in the ArrayList that has a specific name? ie:

ArrayList<Variable> vars = new ArrayList<Variable>();
//Fill with values here//
for (int j = 0; j < vars.size(); j++) {
    String nName = vars.get(j).getName();
    //not real code, but what I would like
    return vars.get(element.getName().equals(nName));
}

At the moment I am trying to accomplish this with lots of for loops and as well as looking ugly it isn't efficient. Thanks!

Upvotes: 0

Views: 6696

Answers (7)

DMe
DMe

Reputation: 7826

With a slight modification to your existing code, you could try:

String n = "nameYouWant";
Variable vFinder(String n) {
    for (v : vars) {
        if v.getName().equals(n) {
            return v;
        }
    }
    return null;
}

Upvotes: -1

davidxxx
davidxxx

Reputation: 131316

This makes no sense and it will not compile :

return vars.get(element.getName().equals(nName));

element.getName().equals(nName) returns a boolean value while vars is a List of Variable.

What you need is probably introduce a method with a parameter that accepts the List of Variable and a String that represents the name and looks for a matching in the List :

public Variable find(List<Variable> vars, String name){
  for (Variable variable : vars) {        
    if (name.equals(variable.getName()){
         return Optional.of(variable);
    }      
  }
  return null;
}

and use it in this way :

List<Variable> vars = new ArrayList<>();
//Fill with values here//
Variable foundVariable = find(vars, "myName");  

Note that with Java 8 you don't need to introduce a method to perform this filter and you could also use Optional to prevent NullPointerException.
You can directly do :

String nameToFind = "myName";
Optional<Variable> variableOpt = vars.stream()
    .filter(v -> nameToFind.equals(v.getName())
    .findAny();
// then unwrap the object from the Option if present
if (variableOpt.isPresent()){
    Variable foundVariable = variable.get();
    // do your processing
}

Upvotes: 0

CodeMatrix
CodeMatrix

Reputation: 2154

Maybe you can use Streams from Java 8 to filter the element out which you need:

Optional<Variable> optionalVariable = vars.stream().filter(element -> element.getName().equals(theNameYouWant)).findFirst();
Variable var = optionalVariable.orElseThrow(() -> new NullPointerException()); //or you use just the Optional#get method instead.

Or you if you're not using Java 8 try this

for(Variable variable : vars) {
    if(variable.getName().equals(theNameYouWant)) {
        return variable;
    }
}

Upvotes: 2

Bushra Hannure
Bushra Hannure

Reputation: 111

I think this code might be useful for you, here i am adding one variable object having name'dummy' in Arraylist and checking for it in the loop

    ArrayList<Variable> list = new ArrayList<>();
    list.add(new Variable("dummy", 1));

    for (Variable obj : list) {
        if(obj.getName().equals("dummy")) {
            return obj;
        }
    }

Upvotes: 1

Evilguy
Evilguy

Reputation: 366

I would recommend you to use Map, it is most efficient way of getting elements without looping through whole array

Variable var = new Variable("name");
Map<String,Variable> vars = new HashMap<>();

vars.put(var.getName(),var);
vars.get("name");

Upvotes: 0

Maurice Perry
Maurice Perry

Reputation: 9651

This should do it:

static Variable findVariable(List<Variable> vars, String name) {
    for (Variable var: vars) {
        if (var.getName().equals(name)) {
            return var;
        }
    }
    return null; // not found
}

Upvotes: 2

curlyBraces
curlyBraces

Reputation: 1105

Using Java-8 streams:

vars.stream()
    .filter(var -> var.getName().equals(someName))
    .collect(Collectors.toList())

Upvotes: 2

Related Questions