Sam Joos
Sam Joos

Reputation: 450

Java: find empty key in map:

I don't know why does not work with me. I have a empty keys in map but I cannot catch them.

Map<String, Long> map = new TreeMap<>();

//put data

map.entrySet().stream().forEach(e -> {
    if (e.getKey().equals("") || e.getKey().equals(" ") || e.getKey() == "" || e.getKey() == " ") {
        map.remove(e.getKey(), e.getValue());
    }
});

Edited: I made a test for value:

     map.entrySet().stream() .forEach(e -> {
            if (e.getValue() == 133835) {
            System.out.println("key empty: " + e.getKey().isEmpty());
            System.out.println("key: >" + e.getKey() + "<");
            System.out.println("val: " + e.getValue());
        }
    });

    map = map.entrySet().stream().filter(
            p -> !"".equals(p.getKey().trim())).
            collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));


map.entrySet().stream() .forEach(e -> {
    if (e.getValue() == 133835) {

        System.out.println("key empty: " + e.getKey().isEmpty());
        System.out.println("key: >" + e.getKey() + "<");
        System.out.println("val: " + e.getValue());
    }
});

the result is:

key empty: false
key: >‏<
val: 133835
key empty: false
key: >‏<
val: 133835

I think this key is a gost )

Upvotes: 0

Views: 6932

Answers (2)

wgitscht
wgitscht

Reputation: 2766

first of all i would generally suggest to trim instead of checking for " " m(one space) and "" (empty string). And secondly that might be the case (a key with more than one space).

  "".equals(e.getKey().trim())

edit example: Map map = new TreeMap();

        map.put("",  1L);
        map.put(" ", 2L);
        map.put("3", 3L);

        map.entrySet().stream().forEach(e -> {
            System.out.println("key empty: " + e.getKey().isEmpty());
            System.out.println("key: >" + e.getKey() + "<");
            System.out.println("val: " + e.getValue());
        });
        map = map.entrySet().stream().filter(
                p -> !"".equals(p.getKey().trim())).
                collect(Collectors.toMap(Entry::getKey, Entry::getValue));        

        map.entrySet().stream().forEach(e -> {
            System.out.println("key empty: " + e.getKey().isEmpty());
            System.out.println("key: >" + e.getKey() + "<");
            System.out.println("val: " + e.getValue());
        });

output is:

key empty: true
key: ><
val: 1
key empty: false
key: > <
val: 2
key empty: false
key: >3<
val: 3
AFTER REMOVAL
key empty: false
key: >3<
val: 3

Upvotes: 0

dan b
dan b

Reputation: 1172

Try using e.getKey().trim().isEmpty()

Upvotes: 1

Related Questions