0

I was having some problem when trying to sort array list of objects. Basically I have populated an object list and the sample data:

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

I populated the array list with the code below:

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);

Then, what I wanted to do is to sort the array list such that for the object with same name, I only get the largest date and put it back to the array but I have no ideas how to do it. Any ideas?

My desired output will be like this:

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

Thanks!

14
  • "Any ideas on how to do it?" Yes, but more importantly, do you have any ideas? And if so, how did it not work to your satisfaction. Commented Oct 29, 2018 at 5:54
  • @GeorgeJempty I am not sure on how or where to start :( Commented Oct 29, 2018 at 6:07
  • What is CalibrationHistoryEntity ? can you provide the class. Commented Oct 29, 2018 at 6:17
  • @Rab It is an object class with CalibrationName and CalibrationDate as attributes! Commented Oct 29, 2018 at 6:19
  • Yes, I need the class, I want to know what Object they are. Provide the class and I will fiddle around with the code. Commented Oct 29, 2018 at 6:20

3 Answers 3

1

A simple way to achieve this is :

  1. grouping by name
  2. for each groups get the maximum date value.
  3. add each maximum to the new list

For example with stream

 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());
Sign up to request clarification or add additional context in comments.

Comments

0

The following simple block will give you what you need. It is also efficient because it is 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);
    }

In the following step we pull the results ... i am doing some sort by name as well (optional)

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

Now let's print results (or use as you wish):

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

Comments

0

Okay, I have done writing the method for you to sort the List here it is

    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();
            }
        }
    }

and the method to get all the index

/**
 * 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;
}

and I made the input via

    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);
    }

This is the output

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

1 Comment

this is not good from performance point of view. you can give a solution with O(n) instead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.