合并两个有序的时间链表
import java.util.ArrayList; import java.util.Comparator; import java.util.List; import com.doudou.database.model.post.Comments; public class SortByDate implements Comparator<Comments> { @Override public int compare(Comments o1, Comments o2) { return o2.getDate().compareTo(o1.getDate()); } /** * 合并两个有序的链表按时间排序 按降序排列 * * @param c1List * @param len1 * @param c2List * @param len2 * @return */ public List<Comments> sortByComments(List<Comments> c1List, int len1, List<Comments> c2List, int len2) { List<Comments> mergeComments = new ArrayList<Comments>(); int i = 0; int j = 0; while (i < len1 && j < len2) { if (compare(c1List.get(i), c2List.get(j)) > 0) { mergeComments.add(c2List.get(j)); j++; } else { mergeComments.add(c1List.get(i)); i++; } } if (i < len1) { while (i < len1) { mergeComments.add(c1List.get(i)); i++; } } if (j < len2) { while (j < len2) { mergeComments.add(c2List.get(j)); j++; } } return mergeComments; } public static void main(String[] args) { List<Comments> listComment1 = new ArrayList<Comments>(); List<Comments> listComment2 = new ArrayList<Comments>(); Comments test1 = new Comments(); test1.setDate("2009-01-01 20:20:20"); Comments test2 = new Comments(); test2.setDate("2005-05-01 02:20:20"); Comments test3 = new Comments(); test3.setDate("2004-05-01 02:20:20"); listComment1.add(test1); listComment1.add(test2); listComment1.add(test3); Comments test4 = new Comments(); test4.setDate("2009-01-01 20:20:20"); Comments test5 = new Comments(); test5.setDate("2009-01-01 10:20:20"); Comments test6 = new Comments(); test6.setDate("2008-02-01 22:25:20"); Comments test7 = new Comments(); test7.setDate("2007-01-01 23:22:20"); Comments test8 = new Comments(); test8.setDate("2005-08-01 18:22:20"); listComment2.add(test4); listComment2.add(test5); listComment2.add(test6); listComment2.add(test7); listComment2.add(test8); int len1 = listComment1.size(); int len2 = listComment2.size(); List<Comments> listComment3 = new SortByDate().sortByComments( listComment1, len1, listComment2, len2); for (Comments c : listComment3) { System.out.println(c.getDate()); } } }
运行结果为:
2009-01-01 20:20:20
2009-01-01 20:20:20
2009-01-01 10:20:20
2008-02-01 22:25:20
2007-01-01 23:22:20
2005-08-01 18:22:20
2005-05-01 02:20:20
2004-05-01 02:20:20

浙公网安备 33010602011771号