【问题标题】:Sorting using comparator使用比较器排序
【发布时间】:2020-10-08 17:16:30
【问题描述】:

我需要使用 Java 8 比较器对 详细信息 类对象列表进行排序


    class Details{
      String name;
      String age;

    }

按照以下偏好的详细信息类名称的顺序

1st--从字母开始

第二个——以数字开头

第三个——以特殊字符开头

预期结果 s/b: sorted List of Details = 根据 Details 名称排序,与类中的其他参数无关

    "Came"

    "result"

    "Result came"

    "01 Result"

    "02 Result"

    "05 Result"

    "# Came"

    "# Result"
    Collections.sort(List.o(details1,details2,details3),(d1,d2)->{

    // got stuck here what to include to achieve the sort as per my requirement

    return d1.getName().compareTo(d2.getName());
    });

【问题讨论】:

  • 到目前为止你有什么尝试?

标签: java list comparator


【解决方案1】:

这是为您准备的 Java 11(刚刚使用 var,仅此而已)代码:

    var a = List.of(details1, details2, details3)
                .stream()
                .sorted(Comparator.comparingInt((Details d) -> priority(d.getName())).thenComparing(Details::getName))
                .collect(Collectors.toList());

如果优先方法难以理解,可以参考@Eklavya的代码


    private static int priority(String str){
        return Character.isAlphabetic(str.charAt(0))?1:Character.isDigit(str.charAt(0))?2:3;
      }

【讨论】:

    【解决方案2】:

    您可以像这样定义自定义优先级

    private static int priority(String str){
        if (Character.isAlphabetic(string.charAt(0)))return 1;
        if (Character.isDigit(string.charAt(0)))     return 2;
        return 3;
    }
    

    然后就可以在比较函数中使用了

    Collections.sort(list, new Comparator<Project>() {
        @Override
        public int compare(Details o1, Details o2) {
            int result = Integer.compare(priority(o1.name), priority(o2.name));
            if (result != 0) return result;
            return o1.name.compareTo(o2.name);
        }
    });
    

    使用 java 8 语法

    Collections.sort(list,Comparator.comparingInt(d -> priority(d.getName()))
                                    .thenComparing(d-> d.getName()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-29
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-11
      相关资源
      最近更新 更多