[英]How to declare and use an array of dictionaries from Python in Java and filter them?
I'd like to understand how dictionaries work in Java, 我想了解字典在Java中的工作方式,
I know that I can do something like 我知道我可以做类似的事情
Map<String, String> map = new HashMap<String, String>();
map.put("dog", "type of animal");
System.out.`println`(map.get("dog"));
But I want to insert something that similar to what we do in python 但是我想插入类似于我们在python中所做的事情
T= []
value= {'name': 'someone', 'age': 13, 'tall': 1.55}
and I can add value to T, so I can filter them later by field ? 并且我可以为T添加值,以便稍后可以按字段过滤它们? Is this doable ?
这可行吗?
UPDATE 更新
In python, I add a list of dict to a list, to easily filter them. 在python中,我将字典列表添加到列表中,以轻松过滤它们。
T= []
a= {'name': 'someone', 'age': 13, 'tall': 1.55}
b= {'name': 'Jack', 'age': 14, 'tall': 1.39}
T.append(a)
T.append(b)
The result: 结果:
T= [ {'name': 'someone', 'age': 13, 'tall': 1.55}, {'name': 'Jack', 'age': 14, 'tall': 1.39}]
I would like to know what is the equivalent structure of these datastructure in python. 我想知道python中这些数据结构的等效结构是什么。 How can I declare varibale like a, and b ?
我如何像a和b这样声明varibale?
filtered_T = [v for v in T if v['name'=='someone']]
this will give 这会给
T= [ {'name': 'someone', 'age': 13, 'tall': 1.55}
In Java, you would typically create a class for this. 在Java中,通常会为此创建一个类。
class Person {
private final String name;
private final int age;
private final double height;
//constructors, etc.
}
Then you would have a data-structure that holds the elements. 然后,您将拥有一个包含元素的数据结构。 A
List<Person>
could perfectly do the job here. List<Person>
可以在这里完美地完成工作。
Person p1 = new Person("someone", 13, 1.55);
Person p2 = new Person("Jack", 14, 1.39);
List<Person> personsList = Arrays.asList(p1, p2);
The list comprehension you have to filter your elements would be written as (with Java 8): 您必须过滤元素的列表理解将写为(对于Java 8):
personsList = personsList.stream()
.filter(p -> p.getName().equals("someone"))
.collect(Collectors.toList());
or 要么
personsList.removeIf(p -> !p.getName().equals("someone"));
Basically, you get the stream from the original list, filter the person instances that have "someone" as their name, and collect the filtered elements into a list, that you assign back to the variable personsList
. 基本上,您从原始列表中获取流,过滤名称为“ someone”的人员实例,并将过滤后的元素收集到一个列表中,然后分配给变量
personsList
。
The second approach removes the element in place in the list. 第二种方法是删除列表中的元素。 Of course it only works if the implementation supports removal of elements.
当然,只有在实现支持删除元素的情况下,它才起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.