Java

Java Map에서 동일한 패턴의 key, value 정보 가져오기

바리새인 2025. 1. 15. 23:18

entrySet() 이용

// Filter entries with keys starting with "DATA"
Map<String, Object> filteredMap = searchForm.entrySet()
        .stream()
        .filter(entry -> entry.getKey().startsWith("DATA"))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

for문 이용

// Extract keys into a list for iteration
List<String> keys = new ArrayList<>(searchForm.keySet());

// Result map to store filtered entries
Map<String, Object> filteredMap = new HashMap<>();

// Use for loop to filter keys starting with "DATA"
for (int i = 0; i < keys.size(); i++) {
    String key = keys.get(i);
    if (key.startsWith("DATA")) {
        filteredMap.put(key, searchForm.get(key));
    }
}

pattern 이용

// Define a regex pattern
String regex = "^DATA.*"; // Matches keys starting with "DATA"
Pattern pattern = Pattern.compile(regex);

// Extract keys into a list for iteration
List<String> keys = new ArrayList<>(searchForm.keySet());

// Result map to store filtered entries
Map<String, Object> filteredMap = new HashMap<>();

// Use for loop to filter keys matching the regex
for (int i = 0; i < keys.size(); i++) {
    String key = keys.get(i);
    Matcher matcher = pattern.matcher(key);
    if (matcher.matches()) {
        filteredMap.put(key, searchForm.get(key));
    }
}