java - 对字符串列表进行排序

标签 java list sorting

我被分配了这个任务:

Complete the function void sort(List l) that sorts a list l that contains the strings "one","two","three","four" (although not necessarily in that order). You should declare a Comparator, and use this with the Collections.sort function. The comparator should use the comp function described above. The list l will be altered when it is sorted.

我已经编写的代码是这样的:

import java.util.*;

public class CW3 {

    private static HashMap < String, Integer > map = new HashMap < String, Integer > ();

    public CW3() {
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);
        map.put("four", 4);

        List listB = Arrays.asList("A", "B", "C");
    }

    public static void main(String[] args) {
        System.out.println(new CW3().comp("one", "two"));
        System.out.println(new CW3().comp("two", "one"));
        System.out.println(new CW3().comp("one", "one"));
    }

    int comp(String s1, String s2) {
        int i1 = map.get(s1);
        int i2 = map.get(s2);
        return (i1 < i2 ? -1 : (i1 == i2 ? 0 : 1));
    }

    void sort(List l) {
        Comparator c = new Comparator() {

            public int compare(Object o1, Object o2) {
                return 0; // FIXME change this so it calls comp
            }
        };
        // now sort l using the comparator c
        // FIXME complete this line
    }

有什么想法从哪里开始吗?它说列表,所以我必须创建一个列表,但是我该如何对它们进行排序?

最佳答案

您需要做的是定义 compare方法。它应该需要两个对象 o1o2作为参数并返回

  • -1o1 < o2
  • 0o1 == o2
  • 1o1 > o2

您的Comparator使用此方法作为决定元素顺序的基础。然后对列表进行排序 l通过调用 Collections.sort(l, c) ,其中cComparator你已经定义了。

关于java - 对字符串列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22332489/

相关文章:

Java 十进制格式 : how to reject "invalid" input with grouped decimals?

python - 如何将 pandas DataFrame 压缩到具有唯一键和列出值的字典中?

java - 如何对包含汉字的列表进行排序

C# 组列表并将计数放入列表变量

java - 如何在java中按整数值的一列对多维字符串数组进行排序?

java - 对行进行排序时,如何在多维数组中交换列?

java - 如何分析 NetBeans Maven 项目中的 JUnit 测试?

java - JPA 一对多在映射后给出空值

java - 将响应从 ServerResource 流式传输回客户端

Python,在列表列表中,将第一个列表的第一个元素与第二个列表的第一个元素进行比较