1
- import java .text .ParseException ;
2
- import java .text .SimpleDateFormat ;
3
1
import java .util .Comparator ;
4
- import java .util .Map ;
5
2
import java .util .Set ;
6
- import java .util .TreeMap ;
7
3
import java .util .TreeSet ;
8
4
9
5
/**
18
14
public class ThirdLatestDate {
19
15
20
16
public Date solve (Date [] dates ) {
21
-
22
- Map <Integer , Set <Date >> sortedDates = new TreeMap <Integer , Set <Date >>(new Comparator <Integer >() {
17
+ Set <Date > sortedDates = new TreeSet <Date >(new Comparator <Date >() {
23
18
@ Override
24
- public int compare (Integer i , Integer j ) {
25
- return j . compareTo (i );
19
+ public int compare (Date i , Date j ) {
20
+ return i . year . compareTo (j . year );
26
21
}
27
-
28
- });
29
-
30
- for (Date date : dates ) {
31
- if (sortedDates .containsKey (date .year )) {
32
- sortedDates .get (date .year ).add (date );
33
- } else {
34
- Set <Date > yearDates = new TreeSet <Date >(new Comparator <Date >() {
35
-
36
- SimpleDateFormat f = new SimpleDateFormat ("dd-MM-yyyy" );
37
-
38
- public int compare (Date d1 , Date d2 ) {
39
-
40
- java .util .Date date1 = null , date2 = null ;
41
- try {
42
- date1 = f .parse (d1 .day + "-" + d1 .month + "-" + d1 .year );
43
- date2 = f .parse (d2 .day + "-" + d2 .month + "-" + d2 .year );
44
- } catch (ParseException e ) {
45
- }
46
- return date2 .compareTo (date1 );
47
- }
48
- });
49
-
50
- yearDates .add (date );
51
- sortedDates .put (date .year , yearDates );
22
+ }.thenComparing (new Comparator <Date >() {
23
+ @ Override
24
+ public int compare (Date i , Date j ) {
25
+ return i .month .compareTo (j .month );
52
26
}
53
- }
54
-
55
- Date thirdLatesDate = null ;
56
- int i = 0 ;
57
- for (Set <Date > sd : sortedDates .values ()) {
58
- for (Date d : sd ) {
59
- thirdLatesDate = d ;
60
- if (i == 2 ) {
61
- return d ;
62
- } else {
63
- i ++;
64
- continue ;
65
- }
27
+ }.thenComparing (new Comparator <Date >() {
28
+ @ Override
29
+ public int compare (Date i , Date j ) {
30
+ return i .day .compareTo (j .day );
66
31
}
67
- }
32
+ })));
68
33
69
- return thirdLatesDate ;
34
+ for (Date date : dates ) {
35
+ sortedDates .add (date );
36
+ }
70
37
38
+ return (Date ) sortedDates .toArray ()[sortedDates .size () - 3 ];
71
39
}
72
40
}
0 commit comments