srikanth
srikanth

Reputation: 978

Group list of objects based on date(hourly)

I have a list of Objects with java.util.date as one of the fields. How to separate/filter Objects based on date(hourly). I.e For example: Objects with a date range from 12.00 to 13:00 should be separated or form a new list and so on for every hour. Help me achieve this.

Upvotes: 2

Views: 3497

Answers (3)

Shubhendu Pramanik
Shubhendu Pramanik

Reputation: 2751

Try below:

List<MyClass> yourFinalList = list.stream().filter(x -> Integer.parseInt(new SimpleDateFormat("HH").format(x.getDate())) >= 12 && Integer.parseInt(new SimpleDateFormat("HH").format(x.getDate())) <= 13).collect(Collectors.toList());

        System.out.println(yourFinalList.size());

Hope your class is like below:

public class MyClass {
    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    Date date;
}

Upvotes: 1

Ward
Ward

Reputation: 2828

You can stream your original list of objects, and then use the groupingBy collector.

This will give you a Map where the keys are the hours, and the values are list of object for that hour.

List<MyObject> objects = new ArrayList<>();

Map<Integer, List<MyObject>> objectsPerHour = objects.stream()
        .collect(Collectors.groupingBy(MyObject::getHour));

I assumed an implementation of MyObject like this (you can implement getHour() like you want):

class MyObject {

    private Date date;

    public int getHour() {
        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()).getHour();
    }
}

Upvotes: 6

DHARMENDRA SINGH
DHARMENDRA SINGH

Reputation: 615

public class DateComparator implements Comparator<XYZ> {
    public int compare(XYZ obj1, XYZ obj2) {
        if (obj1.getDate().before(obj2.getDate()) {
            return -1;
        } else if (obj1.getDate().after(obj2.getDate()) {
            return 1;
        } else {
            return 0;
        }        
    }
}

Upvotes: 0

Related Questions