有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何根据键获取HashMap值?

因此,我有一个ArrayList,其中包含的对象有名称、id、薪水等,还有一个队列,其中包含另一个ArrayList对象、型号、年份等。 我创建了一个HashMap,使用ArrayList对象作为键,队列作为值,将每个队列与ArrayList中的一个对象相关联

问题是,我必须列出一个确定键的所有值。 我想知道如何根据对象的名称值返回hashmap的所有值

例如,这是我的地图:

{Mech[Name=Ella McCarthy,ID=1]=[Car[model=Civic,year=2010,fix=flat ters],Car[model=Audi A3,year=2012,fix=some breaked]

Mech[Name=Josh Reys,ID=1]=[Car[model=Cruze,year=2014,fix=something breaked],Car[model=Impala,year=1990,fix=something breaked]]

如果键中对象的名称等于Ella McCarthy,是否有任何方法返回值


共 (1) 个答案

  1. # 1 楼答案

    下一个代码可能对您很全面:

    public class MapExample {
    private static final String DETERMINED_KEY = "Ella McCarthy";
    
    Queue<Car> queue = new PriorityQueue<>();
    Map<Mech, Queue<Car>> map = new HashMap<>();
    
    Queue<Car> getValuesByNameInKeyObjectWithStreams() {
        Queue<Car> cars = map.entrySet()
                .stream()
                .filter(mapEntry -> mapEntry.getKey().getName().contentEquals(DETERMINED_KEY))
                .map(Map.Entry::getValue)
                .findFirst()
                .orElseThrow(); // Throw exception if did't find according value. Or return another result with orElse(result)
    
        return cars;
    }
    
    Queue<Car> getValuesByNameInKeyObjectBeforeJava8() {
        for (Map.Entry<Mech, Queue<Car>> entry : map.entrySet()) {
            String mechName = entry.getKey().getName();
    
            if (mechName.equals(DETERMINED_KEY)) {
                return entry.getValue();
            }
        }
    
        // Throw exception or return another result
        throw new  RuntimeException("If didn't find exception");
    }
    

    }

    class Mech {
    String name;
    
    public String getName() {
        return name;
    }
    

    }

    class Car {
    String value;
    

    }

    如果您喜欢函数式风格并使用Java8或更高版本,请查看getValuesByNameInKeyObjectWithStreams方法