猿问

如何按日期对列表进行排序,然后搜索元素并设置在第一个位置

我正在搜索如何对列表中的元素进行排序,然后通过 getType 获取值 .. 如果 getType == 0 将 y 设置为列表中的第一个元素(但不替换 0 个位置中的项目。)其他人不需要按类型订购它们。


我在我的代码中做了两个比较。首先,我通过 getDate 订购了它们……其次,我通过 getType 订购了它们。但当然,我的方法返回的最后一个列表是按类型排序的列表。我不想要那个。


public List<PromotionList> returnSortedList(List<PromotionList> inputList) {

        Collections.sort(inputList, (o1, o2) -> {

            if (o1.getDate() != null) {

                SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a", Locale.ENGLISH);

                try {

                    return format.parse(o2.getDate()).compareTo(format.parse(o1.getDate()));

                } catch (ParseException e) {

                    e.printStackTrace();

                 //   Log.e("ErrorGetDate", e.getMessage());

                    return 0;

                }

            }


            return 0;

        });


        Collections.sort(inputList, (o1, o2) -> {

            if (o1.getType() != null && o2.getType() != null) {

                if (o1.getPrioridad() == 0) {

                    int prior1 = o1.getType();

                    int prior2 = o2.getType();

                    return Integer.compare(prior1, prior2);

                }

            }

            return 0;


        return inputList;

    }

谢谢。


jeck猫
浏览 199回答 2
2回答

手掌心

我假设您想首先按日期对列表进行排序,如果有两个日期相同的项目,您想按类型对它们进行排序。我会这样做:Collections.sort(myList, new Comparator<PromotionList>() {&nbsp;&nbsp; &nbsp;public int compare(PromotionList o1, PromotionList o2) {&nbsp;&nbsp; &nbsp; &nbsp;if (o1.getDateTime() == null || o2.getDateTime() == null) return 0;&nbsp;&nbsp; &nbsp; &nbsp;int a = o1.getDateTime().compareTo(o2.getDateTime());&nbsp;&nbsp; &nbsp; &nbsp;if(a == 0) {&nbsp; &nbsp; &nbsp; &nbsp; if (o1.getType() == null || o2.getType() == null) return 0;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; return o1.getType().compareTo(o2.getType());&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;return a;&nbsp; &nbsp; }&nbsp;&nbsp; });
随时随地看视频慕课网APP

相关分类

Java
我要回答