gpt4 book ai didi

java - 从 Map> 交换键

转载 作者:行者123 更新时间:2023-12-02 12:44:03 24 4
gpt4 key购买 nike

我正在寻找这个问题的解决方案(用于考试):

我有一个由函数填充的 Map < String, SortedSet < String >> 运算符

public void addOperator(String operatorName, String... destinationNames) throws ProposalException {
if(operators.containsKey((operatorName))){
throw new ProposalException("Operator " + operatorName + "already into system!");
}
else{
SortedSet<String> destinationstemp=new TreeSet<>();
for(String s: destinationNames){
if(s!=null){
destinationstemp.add(s);
}
}
operators.put(operatorName, destinationstemp);


}

现在,我想创建一个新的 Map < String, SortedSet < String >> destinations ,其键为 destinationName,值为相关的operatorNames。

我该如何解决这个问题?

P.S:上面这个是方法的用法,代码之外的部分是想要的输出。很抱歉代码格式错误。 ph 是外观模式类的实例

    public SortedSet<String> getDestOperators(String destinationName) {...}//method that returns the **destinations** values related to destinationName}
ph.addOperator("op3","london","rome");
ph.addOperator("op2","london","berlin");
ph.addOperator("op5","berlin","rome","madrid");
ph.addOperator("op1","london","madrid","berlin");
ph.addOperator("op10","rome");
ph.addOperator("op4","madrid","berlin");
System.out.println(ph.getDestOperators("madrid"));

输出:[op1, op4, op5]

最佳答案

您需要遍历映射中的每个条目并检查内部集合是否包含您要检查的值,

public SortedSet<String> getDestOperators(String destinationName) {
Set<String> result = new HashSet<String>();
for(Map.Entry<String,Set<String>> entry : operators.getValues()){

if(entry.getValue().contains(destinationName)){
results.add(entry.getKey());
}
}

return result;
}

关于java - 从 Map<Key, List<Values>> 交换键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44846742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com