gpt4 book ai didi

java - 在java中存储(UniqueString, String)

转载 作者:行者123 更新时间:2023-12-01 16:52:49 25 4
gpt4 key购买 nike

存储一对值,其中只有一个值是唯一的。

输入:添加(字符串,字符串)

49.205.119.239, hello
14.192.212.57, yollo
49.205.119.239, tello
14.192.212.57, bella

预期输出:

49.205.119.239, hello
14.192.212.57, yollo

我尝试了下面的代码。 uniqueIp.putIfAbsent(line,actualLine); 接受所有值,甚至重复的键(行)。

public static void processLine(String actualLine) throws IOException {
GetLocationExample obj = new GetLocationExample();
Map<String, String> uniqueIp = new HashMap<String, String>();
Pattern pattern = Pattern.compile("([(]100.0)[)][\\]][:]*");
Matcher matcher = pattern.matcher(actualLine);
String ip = null;
String line = null ;
if (matcher.find())
{
ip= "100%";
Pattern pattern1 = Pattern.compile("\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
Matcher matcher1 = pattern1.matcher(actualLine);

if (matcher1.find())
{ line= (matcher1.group(0));
uniqueIp.putIfAbsent(line, actualLine);
}

else { System.out.println("Not Present"); }
}
else { return; }

for (String name: uniqueIp.keySet())
{
String key =name.toString();
String value = uniqueIp.get(name).toString();
System.out.println(key + " " + value);
}

尝试了if(!uniqueIp.containsKey(key))。没有成功

最佳答案

不必像大家建议的那样通过调用 containsKey() 进行保护,只需使用 putIfAbsent()方法:

Map<String,String> map = new HashMap<>();
map.putIfAbsent("a1", "hello");
map.putIfAbsent("b1", "yollo");
map.putIfAbsent("a1", "tello");
map.putIfAbsent("b1", "bella");

关于java - 在java中存储(UniqueString, String),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36558203/

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