gpt4 book ai didi

java - 我们如何在键不重复的列表中添加 Elasticsearch 结果(searchResponse)键和值

转载 作者:行者123 更新时间:2023-12-02 04:29:10 26 4
gpt4 key购买 nike

我们如何在列表中添加 Elasticsearch 结果(searchResponse)键和值,而不希望列表中出现重复的键?因为我们想从函数返回一个列表。

      for (int i = 0; i < hits.totalHits(); i++) {      
responseFields = (Map<String, Object>) hits.getAt(i).getSource();
Student st=new Student();
Iterator it = responseFields.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
//use list here
System.out.println(pair.getKey() + " = " + pair.getValue()+);
}}

在这种情况下,每次我们为每个 for 循环迭代获得重复的键。根据要求,我应该将结果保存在具有单个键的列表中。这可以在表表示中制作标题。

最佳答案

一套几乎就是您想要的。这是一个特殊的列表,不允许重复(这是一个严重的过度简化)。

      Set uniqueValues = new HashSet<Entry>();
for (int i = 0; i < hits.totalHits(); i++) {
responseFields = (Map<String, Object>) hits.getAt(i).getSource();
Student st=new Student();
Iterator it = responseFields.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
uniqueValues.add(pair);
//use list here

}}

这应该可行,但前提是键和值对都必须是唯一的。

编辑:我刚刚发现如果出现重复项,您需要执行某些操作。为此,您只需使用 uniqueValues.contains() 方法即可。它会告诉您它是否已在集合中。所以:

if(!uniqueValues.contains(pair))
uniqueValues.add(pair)
else addToTableOrSomething

如果您只是希望键是唯一的,您可以使用映射。它允许您仅对 key 执行 cointains() 操作。

      Map uniqueValues = new HashMap<Something, Somthing>();
for (int i = 0; i < hits.totalHits(); i++) {
responseFields = (Map<String, Object>) hits.getAt(i).getSource();
Student st=new Student();
Iterator it = responseFields.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
if(!uniqueeValues.contains(pair.getKey())
uniqueValues.put(pair.getKey(), pair.getValue());
else doSomthingElse

//use list here

}}

关于java - 我们如何在键不重复的列表中添加 Elasticsearch 结果(searchResponse)键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31721206/

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