gpt4 book ai didi

java - JXPath : how to query all keys from a map

转载 作者:行者123 更新时间:2023-12-02 00:44:38 24 4
gpt4 key购买 nike

我正在尝试查询 map 中所有项目的属性。

我可以用集合来做到这一点,但它不适用于 map 。

我尝试了很多变体,但没有找到一种方法来获取 map 中对象的所有 id。

请参阅下面的完整代码示例。

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

最佳答案

发现它:“foes/*/id”有效。

有点明显

关于java - JXPath : how to query all keys from a map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57909456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com