Search code examples
javatreemap

JAVA: get variable of object using tree map method


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

Solution

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