仅通过Date组件从DateTime对象列表中删除重复项

时间:2016-10-20 16:21:10

标签: scala list datetime jodatime

从列表Joda DateTime对象中删除重复项的首选方法是什么,但仅限日期组件(无时间组件)

var dates = List[DateTime]()

dates = dates ::: List(new DateTime(2015, 1, 1, 0, 0, 0, 0))
dates = dates ::: List(new DateTime(2011, 1, 1, 0, 0, 0, 1))
dates = dates ::: List(new DateTime(2011, 1, 1, 0, 0, 0, 0)) // different millisOfSecond

println(dates.distinct)

结果

List(2015-01-01T00:00:00.000+01:00,
     2011-01-01T00:00:00.001+01:00,
     2011-01-01T00:00:00.000+01:00)

3 个答案:

答案 0 :(得分:2)

编写一个包装器案例类并覆盖equals方法,以根据日期组件执行相等。

case class DateTimeWrapper(dt: DateTime) {
  override def equals(obj: scala.Any): Boolean = obj match {
    case x: DateTimeWrapper => x.dt.getDayOfMonth == this.dt.getDayOfMonth
    case _ => false
  }
}

以下是使用distinct选择非重复元素的Set方法

def distincts(list: List[DateTime]): List[DateTime] = {
  def helper(set: Set[DateTimeWrapper], list: List[DateTimeWrapper]) = list match {
    case Nil => set
    case x :: xs => if (set contains x) set else set + x
  }
  helper(Set.empty[DateTimeWrapper], list.map(DateTimeWrapper)).toList.map(_.dt)
}

编写一个Implicit以使API看起来更好

implicit class ListUtils(list: List[DateTime]) {
  def distinctElems = distincts(list)
}

用法:

val dates = List(
  new DateTime(2015, 1, 1, 0, 0, 0, 0),
  new DateTime(2011, 1, 1, 0, 0, 0, 1),
  new DateTime(2011, 1, 1, 0, 0, 0, 0)
)

println(dates.distinctElems.length)

答案 1 :(得分:1)

使用JodaTime DateTimeComparator.getDateOnlyInstance()方法。这为您提供了一个DateTimeComparator,它只按日期进行比较。请参阅http://www.joda.org/joda-time/apidocs/index.html?org/joda/time/DateTimeComparator.html

上的API

答案 2 :(得分:0)

我是这样做的:

def orderAndDeleteDuplicatesList(unorderedList: List[DateTime]): List[DateTime] ={


if(unorderedList == Nil || unorderedList.isEmpty) return unorderedList


//order by millis
val sortedList : List[DateTime] =  unorderedList.sortBy(_.getMillis)
var previousElement :Option[DateTime] = None
var purgedAndSortedList = List[DateTime]() //return list
sortedList.foreach ( element  => {

  //Ako trenutni element nije jednak prethodnom ili je prethodni prazan dodaj ga na listu
  if(previousElement.isEmpty || dtc.compare(previousElement.get, element) != 0 ){
    purgedAndSortedList = purgedAndSortedList ::: List(element)
  }

  previousElement = Option(element)

})

purgedAndSortedList
}

DateComparator:

import org.joda.time.{DateTime, DateTimeComparator}

private val dtc: DateTimeComparator = DateTimeComparator.getDateOnlyInstance