programing tip

날짜별로 ArrayList의 객체를 정렬 하시겠습니까?

itbloger 2020. 6. 30. 20:55
반응형

날짜별로 ArrayList의 객체를 정렬 하시겠습니까?


내가 찾은 모든 예제는 알파벳순 으로이 작업을 수행하는 반면 날짜별로 정렬 된 요소가 필요합니다.

내 ArrayList에는 데이터 멤버 중 하나가 DateTime 개체 인 개체가 포함되어 있습니다. DateTime에서 함수를 호출 할 수 있습니다.

lt() // less-than
lteq() // less-than-or-equal-to

그래서 비교하려면 다음과 같이 할 수 있습니다.

if(myList.get(i).lt(myList.get(j))){
    // ...
}

if 블록 안에서 무엇을해야합니까?


객체를 비슷하게 만들 수 있습니다.

public static class MyObject implements Comparable<MyObject> {

  private Date dateTime;

  public Date getDateTime() {
    return dateTime;
  }

  public void setDateTime(Date datetime) {
    this.dateTime = datetime;
  }

  @Override
  public int compareTo(MyObject o) {
    return getDateTime().compareTo(o.getDateTime());
  }
}

그런 다음 다음을 호출하여 정렬합니다.

Collections.sort(myList);

그러나 때로는 여러 다른 속성을 정렬하려는 경우와 같이 모델을 변경하지 않으려는 경우가 있습니다. 이 경우 즉시 비교기를 만들 수 있습니다.

Collections.sort(myList, new Comparator<MyObject>() {
  public int compare(MyObject o1, MyObject o2) {
      return o1.getDateTime().compareTo(o2.getDateTime());
  }
});

그러나 위의 내용은 비교할 때 dateTime이 null이 아닌 경우에만 작동합니다. NullPointerExceptions을 피하기 위해 null을 처리하는 것이 현명합니다.

public static class MyObject implements Comparable<MyObject> {

  private Date dateTime;

  public Date getDateTime() {
    return dateTime;
  }

  public void setDateTime(Date datetime) {
    this.dateTime = datetime;
  }

  @Override
  public int compareTo(MyObject o) {
    if (getDateTime() == null || o.getDateTime() == null)
      return 0;
    return getDateTime().compareTo(o.getDateTime());
  }
}

또는 두 번째 예에서 :

Collections.sort(myList, new Comparator<MyObject>() {
  public int compare(MyObject o1, MyObject o2) {
      if (o1.getDateTime() == null || o2.getDateTime() == null)
        return 0;
      return o1.getDateTime().compareTo(o2.getDateTime());
  }
});

Java 8부터 List 인터페이스는 정렬 방법을 제공합니다 . 람다 식과 결합 하면 가장 쉬운 해결책은

// sort DateTime typed list
list.sort((d1,d2) -> d1.compareTo(d2));
// or an object which has an DateTime attribute
list.sort((o1,o2) -> o1.getDateTime().compareTo(o2.getDateTime()));
// or like mentioned by Tunaki
list.sort(Comparator.comparing(o -> o.getDateTime()))

Collections.sort 메소드를 사용할 수 있습니다. 정적 방법입니다. 리스트와 비교기를 전달합니다. 목록에 대해 수정 된 병합 정렬 알고리즘을 사용합니다. 그렇기 때문에 쌍 비교를 수행하려면 비교기를 전달해야합니다.

Collections.sort(myList, new Comparator<MyObject> {
   public int compare(MyObject o1, MyObject o2) {
      DateTime a = o1.getDateTime();
      DateTime b = o2.getDateTime();
      if (a.lt(b)) 
        return -1;
      else if (a.lteq(b)) // it's equals
         return 0;
      else
         return 1;
   }
});

myList가 비교 가능한 유형 (Comparable 인터페이스를 구현하는 유형) (예 : 날짜, 정수 또는 문자열) 인 경우 비교기를 생략하면 자연 순서가 사용됩니다.


list.sort(Comparator.comparing(o -> o.getDateTime()));

Java 8 람다를 사용하는 Tunaki의 가장 좋은 답변 IMHO


감안할 때 MyObject가 그 DateTime로모그래퍼 회원을 getDateTime()방법, 당신은 정렬 할 수 있습니다 ArrayList포함 된 MyObject바이 요소 DateTime같은 객체를 :

Collections.sort(myList, new Comparator<MyObject>() {
    public int compare(MyObject o1, MyObject o2) {
        return o1.getDateTime().lt(o2.getDateTime()) ? -1 : 1;
    }
});

This is how I solved:

Collections.sort(MyList, (o1, o2) -> o1.getLastModified().compareTo(o2.getLastModified()));

Hope it help you.


With introduction of Java 1.8, streams are very useful in solving this kind of problems:

Comparator <DateTime> myComparator = (arg1, arg2) 
                -> {
                    if(arg1.lt(arg2)) 
                       return -1;
                    else if (arg1.lteq(arg2))
                       return 0;
                    else
                       return 1;
                   };

ArrayList<DateTime> sortedList = myList
                   .stream()
                   .sorted(myComparator)
                   .collect(Collectors.toCollection(ArrayList::new));

All the answers here I found to be un-neccesarily complex for a simple problem (at least to an experienced java developer, which I am not). I had a similar problem and chanced upon this (and other) solutions, and though they provided a pointer, for a beginner I found as stated above. My solution, depends on where in the the Object your Date is, in this case, the date is the first element of the Object[] where dataVector is the ArrayList containing your Objects.

Collections.sort(dataVector, new Comparator<Object[]>() {
    public int compare(Object[] o1, Object[] o2) {
        return ((Date)o1[0]).compareTo(((Date)o2[0]));
    }
});

This may be an old response but I used some examples from this post to create a comparator that would sort an ArrayList of HashMap<String, String> by one object in the list, that being the timestamp.

I have these objects:

ArrayList<Map<String, String>> alList = new ArrayList<Map<String, String>>();

The map objects are as follows:

Map<String, Object> map = new HashMap<>();
        // of course this is the actual formatted date below in the timestamp
        map.put("timestamp", "MM/dd/yyyy HH:mm:ss"); 
        map.put("item1", "my text goes here");
        map.put("item2", "my text goes here");

That mapping is what I use to load all my objects into the array list, using the alList.add(map) function, within a loop.

Now, I created my own comparator:

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

 public class DateSorter implements Comparator {
     public int compare(Object firstObjToCompare, Object secondObjToCompare) {
    String firstDateString = ((HashMap<String, String>) firstObjToCompare).get("timestamp");
    String secondDateString = ((HashMap<String, String>) secondObjToCompare).get("timestamp");

    if (secondDateString == null || firstDateString == null) {
        return 0;
    }

    // Convert to Dates
    DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
    DateTime firstDate = dtf.parseDateTime(firstDateString);
    DateTime secondDate = dtf.parseDateTime(secondDateString);

    if (firstDate.isAfter(secondDate)) return -1;
    else if (firstDate.isBefore(secondDate)) return 1;
    else return 0;
    }
}

I can now just call the Comparator at any time on the array and it will sort my array, giving me the Latest timestamp in position 0 (top of the list) and the earliest timestamp at the end of the list. New posts get put to the top basically.

Collections.sort(alList, new DateSorter());

This may help someone out, which is why I posted it. Take into consideration the return statements within the compare() function. There are 3 types of results. Returning 0 if they are equal, returning >0 if the first date is before the second date and returning <0 if the first date is after the second date. If you want your list to be reversed, then just switch those two return statements! Simple =]


Pass the ArrayList In argument.

    private static void order(ArrayList<Object> list) {

    Collections.sort(list, new Comparator() {

        public int compare(Object o2, Object o1) {

            String x1 =  o1.Date;
            String x2 =  o2.Date;

                return  x1.compareTo(x2);

        }
    });
}

Use the below approach to identify dates are sort or not

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");

boolean  decendingOrder = true;
    for(int index=0;index<date.size() - 1; index++) {
        if(simpleDateFormat.parse(date.get(index)).getTime() < simpleDateFormat.parse(date.get(index+1)).getTime()) {
            decendingOrder = false;
            break;
        }
    }
    if(decendingOrder) {
        System.out.println("Date are in Decending Order");
    }else {
        System.out.println("Date not in Decending Order");
    }       
}   

The Date class already implements Comparator interface. Assuming you have the class below:

public class A {

    private Date dateTime;

    public Date getDateTime() {
        return dateTime;
    }

    .... other variables

}

And let's say you have a list of A objects as List<A> aList, you can easily sort it with Java 8's stream API (snippet below):

import java.util.Comparator;
import java.util.stream.Collectors;

...

aList = aList.stream()
        .sorted(Comparator.comparing(A::getDateTime))
        .collect(Collectors.toList())

참고URL : https://stackoverflow.com/questions/5927109/sort-objects-in-arraylist-by-date

반응형