【问题标题】:How to get max value by specified key from Map in javajava - 如何从Map中的指定键获取最大值
【发布时间】:2016-02-19 20:30:48
【问题描述】:

我有来自文档的列表分数句子,每个最大分数都将插入到每个索引中。例如:

索引 0 = 0.1

索引 1 = 0.3

索引 2 = 0.2

索引 3 = 0.5

索引 4 = 0.4

索引 5 = 0.6

列表分数的索引将设置为Mapvalue,列表文档的key为:

文件 1

文件 2

文件 3

在我使用 Map<listDocuments, Index> 循环后,我得到了这样的列表

文档 1 = 索引 0

文档 1 = 索引 1

文档 1 = 索引 2

文档 2 = 索引 3

文档 2 = 索引 4

文档 3 = 索引 5

问题是,我无法显示具有最大值的文档,并且我只能像这样获取每个文档的最后一个value

文档 1 = 索引 2

文档 2 = 索引 4

文档 3 = 索引 5

虽然我想根据下面的最大值显示它。

文档 1 = 索引 1 (0.3)

文档 2 = 索引 3 (0.5)

文档 3 = 索引 5 (0.6)

这是我的代码

int index = 0;
int index2 = 0;
double max = 0.0;
double max2 = 0.0;

LinkedHashMap< List<Integer>, Integer> data = new LinkedHashMap< List<Integer>, Integer>();

 for (int d1 = 0; d1 < d - 1; d1++) {
     for (int d2 = d1 + 1; d2 < d; d2++) {

          //...Other code.....

     }

     listSentence.add(ste.maxScore());
     listSentence2.add(ste.maxScore2());

     max = Collections.max(listSentence);
     max2 = Collections.max(listSentence2);

     index = listSentence.indexOf(max);
     index2 = listSentence.indexOf(max2);

     data.put(d1, index);
     data.put(d2, index2);
}

//code for displaying it

for (Map.Entry list : data.entrySet()) {
      System.out.println("" + stemmings
                    .get(list.getKey().hashCode())
                    .get(list.getValue().hashCode()));
}

任何答案将不胜感激。谢谢

【问题讨论】:

  • 如果您使用您的文档作为 Key ofc,则每个文档只有一个索引。钥匙只能出现一次。
  • 是的,我是这么想的,但我不知道根据上面显示的内容来使用它
  • 我建议将您的文档用作Key,并将您的索引的ListSet 用作Value。最后,您遍历用作ValueCollection 并记住得分最高的索引。
  • 或者你检查一个索引是否已经存在为Value,如果新索引的分数更高,则覆盖它
  • 你能给出一些代码吗?或在上面修改我的代码。 .谢谢之前

标签: java list dictionary data-structures hashmap


【解决方案1】:

好吧,一个简单的例子:

Map<Integer, Set<Integer>> data = new HashMap<Integer, Set<Integer>>();
for(;;) // use your loop here
{
    int document;
    int index;
    // Do some stuff to get index and so on
    if(!data.containsKey(document))
    {
        data.put(document, new HashSet<Integer>());
    }
    data.get(document).add(index);
}

// Output

for(Map.Entry<Integer, Set<Integer>> entry : data.entrySet())
{
    int maxIndex = -1;
    int maxScore = Integer.MIN_VALUE;
    for(Integer index : entry.getValue())
    {
        int score;
        //get the score for index
        if(score > maxScore)
        {
            maxScore = score;
            maxIndex = index;
        }
    }
    System.out.println("Document: "+entry.getKey()+" Index with max score: "+maxIndex);
}

【讨论】:

  • 好的,谢谢。我会尝试该代码并很快再次返回。 .
  • 谢谢!! .在我尝试使用我的代码进行每次修改后,它就可以工作了。 .
猜你喜欢
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 2021-01-26
  • 1970-01-01
  • 2015-10-20
  • 1970-01-01
相关资源
最近更新 更多