Filip
Filip

Reputation: 1068

JXPath : how to query all keys from a map

I am trying to query a property of all items in a map.

I can do it with a collection, but it does not work for map.

I have tries many variation, but did not find a way to get all ids of objects in map.

See complete code example below.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.jxpath.JXPathContext;

public class TestMap {

    public static void main(String[] args) {

        Person p = createPerson(1);

        p.foes = new HashMap<>();
        p.foes.put("a", createPerson(2));
        p.foes.put("b", createPerson(3));

        p.friends = new ArrayList<>();
        p.friends.add(createPerson(4));
        p.friends.add(createPerson(5));

        //works
        Iterator<Object> friendsId = JXPathContext.newContext(p).iterate("friends/id");
        friendsId.forEachRemaining(o -> System.out.println(o));

        // works
        Iterator<Object> foesId = JXPathContext.newContext(p).iterate("foes/a/id");
        foesId.forEachRemaining(o -> System.out.println(o));

        // does not works :(
        foesId = JXPathContext.newContext(p).iterate("foes/id");
        foesId.forEachRemaining(o -> System.out.println(o));

    }

    private static Person createPerson(Integer id) {
        Person p = new Person();
        p.setId(id);
        return p;
    }

    public static class Person {
        private Integer id;
        private List<Person> friends;
        private Map<String, Person> foes;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public List<Person> getFriends() {
            return friends;
        }

        public void setFriends(List<Person> friends) {
            this.friends = friends;
        }

        public Map<String, Person> getFoes() {
            return foes;
        }

        public void setFoes(Map<String, Person> foes) {
            this.foes = foes;
        }
    }

}

https://commons.apache.org/proper/commons-jxpath/users-guide.html#Map_Element_Access

Upvotes: 0

Views: 372

Answers (1)

Filip
Filip

Reputation: 1068

found it : "foes/*/id" works.

A bit obvious

Upvotes: 0

Related Questions