String CaseInsensitiveOrder TreeMap Keys

Build case-insensitive key lookups with String.CASE_INSENSITIVE_ORDER: a TreeMap treats differently-cased duplicates as one key, so headers match any spelling.

JavaData Integrity

Code

snippet
import java.util.Map;
import java.util.TreeMap;

public class CaseInsensitiveKeys {

    public static void main(String[] args) {
        // HTTP 头式查找:键的大小写不敏感
        Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);

        headers.put("Content-Type", "application/json");
        headers.put("content-length", "42");

        // 大小写不同的同名键视为同一个键:直接覆盖,而不是多存一条
        headers.put("CONTENT-TYPE", "text/html");

        System.out.println("get any case: " + headers.get("content-type"));
        System.out.println("size: " + headers.size());
        System.out.println("contains: " + headers.containsKey("CONTENT-LENGTH"));
    }
}

How it works

String CaseInsensitiveOrder TreeMap Keys comes down to the class CaseInsensitiveKeys and the function main.

Using it

Running the file prints labeled results such as get any case:, size:, contains: — each operation’s effect is visible in the output.

Key statements

Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
headers.put("Content-Type", "application/json");
headers.put("CONTENT-TYPE", "text/html");

Interactive Tools for This Topic

FAQ

What does String CaseInsensitiveOrder TreeMap Keys print when run?
Execute the whole file; each printed line is prefixed with a label like `get any case:`, `size:`, `contains:`.