Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fixes #2277 move MapUtil to light-4j utility module #2278

Merged
merged 1 commit into from
Jul 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions utility/src/main/java/com/networknt/utility/MapUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.networknt.utility;
import java.util.Iterator;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

public class MapUtil {
// Method to get value from HashMap with case-insensitive key lookup
public static <V> Optional<V> getValueIgnoreCase(Map<String, V> map, String key) {
for (Map.Entry<String, V> entry : map.entrySet()) {
if (Objects.equals(entry.getKey().toLowerCase(), key.toLowerCase())) {
return Optional.of(entry.getValue());
}
}
return Optional.empty();
}

// Method to delete value from HashMap with case-insensitive key lookup
public static <V> Optional<V> delValueIgnoreCase(Map<String, V> map, String key) {
for(Iterator<Map.Entry<String, V>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, V> entry = it.next();
if (Objects.equals(entry.getKey().toLowerCase(), key.toLowerCase())) {
it.remove();
return Optional.of(entry.getValue());
}
}
return Optional.empty();
}

}
26 changes: 26 additions & 0 deletions utility/src/test/java/com/networknt/utility/MapUtilTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.networknt.utility;


import org.junit.Assert;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static com.networknt.utility.MapUtil.getValueIgnoreCase;

public class MapUtilTest {
@Test
public void testGetValueIgnoreCase() {
Map<String, String> hashMap = new HashMap<>();
hashMap.put("Key1", "Value1");
hashMap.put("Key2", "Value2");

// Get value from HashMap with case-insensitive key lookup
String key = "key1";
Optional<String> value = getValueIgnoreCase(hashMap, key);
Assert.assertTrue(value.isPresent());
}

}