Reputation: 49
My Class:
public class Proposal {
Date createDate;
// ...
}
We have two objects java.util.Date
and know for sure that the objects of this collection are between these two dates. How to divide these objects by day between these dates, so that I can get a list of these objects by date?
Upvotes: 0
Views: 3653
Reputation:
As of Java 8 this can be accomplished seamlessly with Collectors.groupingBy
:
Map<Date, List<Proposal>> groupedByDate = proposals.stream()
.collect(Collectors.groupingBy(Proposal::getDate));
Upvotes: 1
Reputation: 1132
Something like this to get one of the lists. List<Object> inDateList = list.stream().filter(o-> startDate< o.createDate && o.createDate< endDate).collect(Collectors.toList());
then List<Object> outDateList = new ArrayList<>(list); outDateList.removeAll(inDateList);
EDIT Just to clarify on my note above.
public Map<String, Set<Proposal>> groupProposals(Iterable<Proposal> proposals) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
return proposals.stream()
//GroupingBy creates the Map<Key, Collection<Something>>
.collect(Collectors.groupingBy(p->sdf.format(p.getCreateDate()),//Creates the Key and buckets
Collectors.mapping(i-> i, Collectors.toSet()))); //what kind of buckets do you want.
}
Upvotes: 0
Reputation: 394
Something like this?
public Map<String, Set<Proposal>> groupProposals(Iterable<Proposal> proposals) {
Map<String, Set<Proposal>> map = new HashMap<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
for (Proposal p : proposals) {
String key = sdf.format(p.getCreateDate());
if (!map.containsKey(key)) {
map.put(key, new HashSet<>());
}
map.get(key).add(p);
}
return map;
}
Upvotes: 3