【问题标题】:How can I get a HashMap value depending on the key? [duplicate]如何根据键获取 HashMap 值? [复制]
【发布时间】:2020-05-14 16:47:25
【问题描述】:

所以我有一个 ArrayList,其中包含具有名称、id、薪水等的对象。还有一个包含另一个 ArrayList 对象、模型、年份等的队列。 我创建了一个 HashMap 并将 ArrayList 对象用作键,将队列用作值,将每个队列与 arraylist 中的一个对象相关联。

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

例如这是我的地图:

{Mech [Name = Ella McCarthy , ID = 1]=[汽车 [model=Civic, year=2010, fix=flat tyres], Car [model=Audi A3, year=2012, fix=something broken]] ,

Mech [Name = Josh Reys,ID = 1]=[汽车 [model=Cruze,年份=2014,修复=损坏的东西],汽车 [model=Impala,年份=1990,修复=损坏的东西]]}

如果键中的对象中的名称等于 Ella McCarthy,有什么方法可以返回值?

【问题讨论】:

标签: java arraylist hashmap queue


【解决方案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;

}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 2013-09-16
    • 2010-12-19
    • 2020-02-16
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多