上课
import org.joda.time.DateTime;
public class Timestamp {
String id;
DateTime timestamp = new DateTime();
public Timestamp(String id, DateTime timestamp){
this.id = id;
this.timestamp = timestamp;
}
}
主要功能
public static void main(String[] args) {
List<Timestamp > list = new ArrayList<Timestamp >();
list .add(new Timestamp ("1"));
list .add(new Timestamp ("2"), new DateTime().plusHours(1));
list .add(new Timestamp ("3"), new DateTime().plusHours(2));
list .add(new Timestamp ("4"), new DateTime().plusHours(3));
list .add(new Timestamp ("5"), new DateTime().plusHours(4));
list .add(new Timestamp ("1"), new DateTime().plusHours(5));
list .add(new Timestamp ("2"), new DateTime().plusHours(6));
list .add(new Timestamp ("3"), new DateTime().plusHours(7));
list .add(new Timestamp ("4"), new DateTime().plusHours(8));
list .add(new Timestamp ("5"), new DateTime().plusHours(9));
list .add(new Timestamp ("6"), new DateTime().plusHours(10));
list .add(new Timestamp ("1"), new DateTime().plusHours(11));
list .add(new Timestamp ("3"), new DateTime().plusHours(12));
list .add(new Timestamp ("7"), new DateTime().plusHours(13));
list .add(new Timestamp ("2"), new DateTime().plusHours(14));
list .add(new Timestamp ("3"), new DateTime().plusHours(15));
list .add(new Timestamp ("4"), new DateTime().plusHours(16));
list .add(new Timestamp ("8"), new DateTime().plusHours(17));
list .add(new Timestamp ("9"), new DateTime().plusHours(18));
list .add(new Timestamp ("10"), new DateTime().plusHours(19));
List<Object> newList = removeDuplicates(list);
}
如何从列表中删除重复的时间戳ID并仅返回该ID的最新时间戳时间。
我尝试使用以下方法,但已经遇到了无法正确删除ID的问题。
public static List<Object> removeDuplicates(List<Timestamp > l) {
// ... the list is already populated
Set<Timestamp > s = new TreeSet<Timestamp >(new Comparator<Timestamp >() {
@Override
public int compare(Timestamp o1, Timestamp o2) {
if (o1.getId().equalsIgnoreCase(o2.getId())) {
return 0;
} else {
return 1;
}
}
});
s.addAll(l);
return Arrays.asList(s.toArray());
}
答案 0 :(得分:0)
答案 1 :(得分:0)
最好是使用TreeSet:
// public class whatever implements Comparator<Bean>
// ...
// public void foo() {
// ...
TreeSet<Bean> ourSet = new TreeSet<Bean>(this);
public int compare(Bean o1,
Bean o2) {
return o1.getDateTime().compareTo(o2.getDateTime());
}
现在使用.first()
获取最低元素,使用.last()
获取最高元素。可能感兴趣的其他方法有lower()
,higher()
,pollFirst()
和pollLast()
。希望有所帮助。
答案 2 :(得分:0)
希望您需要获取TimeStamp列表,如果2个时间戳具有相同的ID,那么您需要获取最新的。 使用Java 8
private static List<Timestamp> removeDuplicates(List<Timestamp> list) {
Map<String, Timestamp> collect = list
.stream()
.collect(Collectors.toMap(Timestamp::getId,
v -> v,
(u, v) -> u.getTimestamp().compareTo(v.getTimestamp()) > 0 ? u : v));
return new ArrayList<>(collect.values());
}