繁体   English   中英

使用方法中传递的参数从 Map 获取一对键+值

[英]Get a pair key+value from a Map with a parameter passed in a method

我需要从 Map 获取键+值(系统的每次迭代只有一对),我编写了这个方法:

public String findValueInMapForExcel(String paramToFind,   Map<String, String> myMap) {
    
    System.out.println("MAP: "+myMap); //Data inside are correct
    System.out.println("KEYSET: "+myMap.keySet()); //Data inside are correct

    //Get key+value without cycle

    return somethingForNow;
}

我需要获取 paramToFind 的键+值记录,可能没有循环,我选择了这种方式,因为这是 Excel 文件创建的一部分,通常有 60/80K 行,我认为最好一次创建 Map 并获得每次迭代的对,而不是为每一行执行一个for循环。 感谢您的任何帮助!

向 map 询问属于您的密钥的值

你似乎工作太努力了。 无需编写方法,只需调用Map#get即可。 无需调用keySet

示例代码。

Map< String , String > colorPlan = Map.of(
    "wall" , "Antique White" ,
    "trim" , "Arctic White" ,
    "accent" , "Flannel Grey" 
) ;

当您手头有钥匙时,请向 map 询问匹配值。

String key = "wall" ; 
String value = colorPlan.get( key ) ;  // Returns "Antique White".

此时,我们手中既有键又有值:“wall”和“Antique White”。

我们可以制作一串。

String output = key + "=" + value ;

墙 = 古董白

Map.Entry

如果想将这两个键和值对象成对传递,我们可以通过调用Map.entry方法创建一个Map.Entry object(注意大写与小写)。

Map.Entry < String , String > entry = Map.entry( key , value ) ;

record

在 Java 16 及更高版本中,您可能更喜欢记录 编译器隐式创建构造函数、getter、 equals & hashCodetoString

record ColorPlanItem ( String surface , String color ) {}

用法。

ColorPlanItem item = new ColorPlanItem( key , value ) ;
…
String surface = item.surface() ; 
String color = item.color() ;

我们可以合并通话。

ColorPlanItem item = new ColorPlanItem( key , map.get( key ) ) ;

添加对 map 中缺失元素的检查。

ColorPlanItem item = new ColorPlanItem( key , Objects.requireNonNull( map.get( key ) ) ) ;

您可以直接使用Map#get获取键的值。

public Map.Entry<String, String> getEntry(String paramToFind,  Map<String, String> myMap) {
    return new AbstractMap.SimpleEntry<>(paramToFind, myMap.get(paramToFind));
}

使用 Java 9+:

public Map.Entry<String, String> getEntry(String paramToFind,  Map<String, String> myMap) {
    return Map.entry(paramToFind, myMap.get(paramToFind));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM