Java根据属性对对象进行排序

时间:2018-10-29 05:50:18

标签: java arrays sorting

尝试对对象的数组列表进行排序时遇到问题。基本上,我已经填充了一个对象列表和示例数据:

name: UNIFORMITY
date: Tue Oct 30 02:48:32 GMT+00:00 2018
name: ROI
date: Wed Oct 31 02:48:32 GMT+00:00 2018
name: UNIFORMITY
date: Wed Oct 31 02:48:32 GMT+00:00 2018

我用以下代码填充了数组列表:

CalibrationHistoryEntity object3 = new CalibrationHistoryEntity();
    object3.setCalibrationName("ROI");
    try {
        object3.setCalibrationDate(dt.parse("Oct 31 02:48:32 GMT+00:00 2018"));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    allCalibrationList.add(object3);

然后,我要做的是对数组列表进行排序,以便对于具有相同名称的对象,我只会得到最大的日期并将其放回数组中,但是我不知道该怎么做。有什么想法吗?

我想要的输出将是这样的:

name: ROI
date: Wed Oct 31 02:48:32 GMT+00:00 2018
name: UNIFORMITY
date: Wed Oct 31 02:48:32 GMT+00:00 2018

谢谢!

4 个答案:

答案 0 :(得分:1)

一种简单的方法是:

  1. 按名称分组
  2. 每个组获取最大日期值。
  3. 将每个最大值添加到新列表中

例如流

 final Map<String, List<CalibrationHistoryEntity>> groupingByName= allCalibrationList.stream()
            .collect(Collectors.groupingBy(CalibrationHistoryEntity::getCalibrationName));
 final List<CalibrationHistoryEntity> list = groupingByName.values()
            .stream().map(it -> Collections.max(it, Comparator.comparing(CalibrationHistoryEntity::getCalibrationDate)))
            .collect(Collectors.toList());

答案 1 :(得分:0)

以下简单的块将为您提供所需的内容。 它也很有效,因为它是O(n)

    Map<String, CalibrationHistoryEntity> unique = new HashMap<String, CalibrationHistoryEntity>();

    for (CalibrationHistoryEntity k : allCalibrationList) {
        CalibrationHistoryEntity temp = unique.getOrDefault(k.Name, null);

        if (temp == null || temp.time.before(k.time))
            unique.put(k.Name, k);
    }

在接下来的步骤中,我们提取结果...我也正在按名称进行排序(可选)

    // Optional but you can sort by name :
    Stream<CalibrationHistoryEntity> result = unique.values().stream()
            .sorted((a, b) -> {
                return a.Name.compareTo(b.Name);
            });

现在让我们打印结果(或根据需要使用):

    // Now you can print
    result.forEach(k -> {
        System.out.println("Name: " + k.Name + ", Time: " + k.time);
    });

答案 2 :(得分:0)

好的,我已经完成了编写方法以供您对列表进行排序

    ListIterator<CalibrationHistoryEntity> listIterator = allCalibrationList.listIterator();
    while (listIterator.hasNext()) {
        CalibrationHistoryEntity calibrationHistoryEntity = listIterator.next();
        //Get all the index
        List<Integer> indexes = findAllByName(allCalibrationList, calibrationHistoryEntity.getCalibrationName());
        if (indexes.size() > 1) {
            List<CalibrationHistoryEntity> calibrationHistoryEntities = new ArrayList<>();
            for (int index : indexes) {
                calibrationHistoryEntities.add(allCalibrationList.get(index));
            }
            //Sort by biggest time
            calibrationHistoryEntities.sort(Comparator.comparing(CalibrationHistoryEntity::getCalibrationDate).reversed());
            for (int i = 1; i < calibrationHistoryEntities.size(); i++) {
                //Remove others
                listIterator.remove();
            }
        }
    }

以及获取所有索引的方法

/**
 * gets all the index via the name
 */
public static List<Integer> findAllByName(List<CalibrationHistoryEntity> allCalibrationList, String name) {
    List<Integer> indexes = new ArrayList<>();
    for (CalibrationHistoryEntity calibrationHistoryEntity : allCalibrationList) {
        if (calibrationHistoryEntity.getCalibrationName().equals(name)) {
            indexes.add(allCalibrationList.indexOf(calibrationHistoryEntity));
        }
    }
    return indexes;
}

我通过输入

    String[] names = {"UNIFORMITY", "Roi", "UNIFORMITY"};
    SimpleDateFormat dt = new SimpleDateFormat("MMM dd hh:mm:ss zzz yyyy");
    Date[] dates = new Date[0];
    try {
        dates = new Date[]{dt.parse("Oct 31 02:48:32 GMT+00:00 2018"),
                dt.parse("Oct 31 02:48:25 GMT+00:00 2018"),
                dt.parse("Oct 31 02:48:37 GMT+00:00 2018")};
    } catch (ParseException e) {
        e.printStackTrace();
    }
    List<CalibrationHistoryEntity> allCalibrationList = new ArrayList<>();
    for (int i = 0; i < names.length; i++) {
        String name = names[i];
        Date date = dates[i];
        CalibrationHistoryEntity calibrationHistoryEntity = new CalibrationHistoryEntity();
        calibrationHistoryEntity.setCalibrationName(name);
        calibrationHistoryEntity.setCalibrationDate(date);
        allCalibrationList.add(calibrationHistoryEntity);
    }

这是输出

Name: Roi Time:Wed Oct 31 05:48:25 GMT+03:00 2018
Name: UNIFORMITY Time:Wed Oct 31 05:48:37 GMT+03:00 2018

答案 3 :(得分:-1)

检查:

    public static void main (String[] args) 
    { 
        ArrayList<Student> ar = new ArrayList<Student>(); 
        ar.add(new Student(111, "bbbb", "london")); 
        ar.add(new Student(131, "aaaa", "nyc")); 
        ar.add(new Student(121, "cccc", "jaipur")); 


        Collections.sort(ar, new Comparator<Student> 
            {
               public int compare(Student a, Student b) 
               { 
                   return a.date.getTime() - b.date.getTime();
                } 
         }  ); 
    }

参考:https://www.geeksforgeeks.org/collections-sort-java-examples/