2

Say I have an object called Car:

public class Car(){
  String model;
  String brand;
  Integer yearReleased;
  float price;
}

and create a treemap of cars called cars:

TreeMap<Integer, Car> cars = new TreeMap<Integer, Car>();

Is there a method wherein I can search up the model of a car in the treelist? Something like .getKey() but allows to search an object variable. I'm trying to create a search function wherein it has a parameter of the treemap and the model to be searched and returns the key.

public searchModel(TreeMap<Integer, Car> list, String model){
  return list.getKey(model);
}
1
  • No, you have to have separate map for that. Commented May 16, 2021 at 15:15

1 Answer 1

1

If there's no relationship between the model and the Integer key of the map, you have no choice but to iterate over all its values:

public List<Car> searchModel(TreeMap<Integer, Car> map, String model){
  return map.values()
            .stream()
            .filter(c -> c.model.equals(model))
            .collect(Collectors.toList());
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for this, I was just wondering how to get the input to be a string or something readable. When I print the list using -Arrays.toString- it it gives me [project.Car@65b3120a] instead
@rr11 You need to override Car's toString() mehos
OP asked to return the key rather than the value. That'd be entrySet().stream().filter(e -> e.getValue().model.equals(model)).map(e -> e.getKey()).toList()

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.