0

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!

1
  • 4
    for loop is useless until you have an if statement before return. It breaks for j = 0 at this moment. Commented Feb 22, 2018 at 8:31

7 Answers 7

2

Using Java-8 streams:

vars.stream()
    .filter(var -> var.getName().equals(someName))
    .collect(Collectors.toList())
Sign up to request clarification or add additional context in comments.

2 Comments

I tried this one, but Eclipse says there's a syntax error on the "->" and won't compile
Ok, this only works on and after Java 8. You must be using an Java older version then.
2

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
}

Comments

2

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

Comments

1

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

Comments

0

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

Comments

0

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
}

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.