【问题标题】:List of items and their scores - need to sort and find their position after sorting物品列表及其分数——需要排序并在排序后找到它们的位置
【发布时间】:2017-03-25 06:08:49
【问题描述】:

我有一个类似物品的清单

项目 - 分数

衬衫 - 1245

手表 - 25

腰带 - 320

鞋 - 540

肥皂 - 110

现在我想按分数对这些项目进行排序


排序位置 - 分数 - 项目

0 - 52 - 手表

1 - 110 - 沙发

2 - 320 - 皮带

3 - 540 - 鞋子

4 - 1245 - 衬衫

现在我需要如果我给项目然后我想知道它的位置

例如:如果我说“衬衫”,那么它应该返回 4。

是否有类似的实用程序可用?没有项目将是 1000,像这样我有 10 个不同的列表。

请帮帮我。

【问题讨论】:

  • 你们有哪些工具、编程语言可用?什么环境,操作系统等?完成这项任务相当容易,但您需要选择要使用的编程语言。
  • 我正在使用 java。
  • 您有任何已经在使用的 java 代码吗?如果是这样,我们需要您进行尝试。请edit 并在您的问题中包含纯文本代码。否则,该站点不是辅导或代码编写服务,尽管有些用户可能愿意提供帮助。另外,看看How to ask a good question
  • 列表是什么格式的?那是文本文件吗?
  • 欢迎来到 Stack Overflow!看起来你可能正在寻求家庭作业帮助。虽然我们对此本身没有任何问题,但请注意这些dos and don'ts,并相应地编辑您的问题。 (即使这不是家庭作业,也请考虑建议。)

标签: java sorting position element


【解决方案1】:

您可以使用集合、比较器。我将向您展示示例代码,这可能会对您有所帮助。

public static void main(String[] args) {
TreeMap items=new TreeMap(new Sorting());

items.put(new ListItems("shirts",1245),1245);
items.put(new ListItems("watches",25),25);

items.put(new ListItems("belts",320),320);

items.put(new ListItems("shoes",540),240);

items.put(new ListItems("soaps",110),110);


ArrayList<ListItems>l=new ArrayList(items.keySet());

for(ListItems list:l)
{

if(list.getItem().equalsIgnoreCase("watches"))
    System.out.println("index is : "+l.indexOf(list));
}
}
}

class ListItems
{
public String getItem() {
    return item;
}
public int getScore() {
    return score;
}
public void setScore(int score) {
    this.score = score;
}
public ListItems(String item,int score) {
    super();
    this.score = score;
    this.item = item;
}
private int score;
private String item;
@Override
public String toString() {
    return "ListItems [score=" + score + ", item=" + item + "]";
}

}
class Sorting implements Comparator<ListItems>
{
@Override
public int compare(ListItems o1, ListItems o2) {
    if(o1.getScore()<o2.getScore())
        return -1;
    if(o1.getScore()>o2.getScore())
        return 1;
    else
        return 0;
    }

}

【讨论】:

    猜你喜欢
    • 2012-03-07
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 2021-03-04
    • 2022-10-04
    • 2021-07-23
    • 1970-01-01
    • 2022-06-13
    相关资源
    最近更新 更多