Compare Partial Object in Java ArrayList

I have an object as follows:

public class Record{
    Int ID;
    String title;
    Date date;
    Duration time;

    public Record createRecord(int ID, String title, Date date, Duration time){
        this.ID= ID;
        this.title = title;
        this.date = date;
        this.time = time;
        return this;
    }
}

I store several objects in a list. When inserting a new record, I need to check if there is already an object in the list with ONLY the same heading and date and replace the time in it.

I am looking for any solution that can reach O (1) time.

+4
source share
3 answers

A search in ArrayList for an existing element will lead you to O (n) in the case of a sorted ArrayList (for example, you will sort records), this will take O (logn) time. Therefore, to achieve the desired functionality, I would use the map structure, indexing by title, and then by date. Something like that:

// Create general records DB
Map<String, Map<Date, Record>> records = new HashMap<>();

// Create sub DB for records with same ID
Map<Date, Record> subRecords = new HashMap<>();

// Assuming you've got from somewhere id, title and rest of the parameters
subRecords.put(recordDate, new Record(id, title, time, duration));
records.put(recordId, subRecords)

// Now checking and updating records as simple as
sub = records.get(someTitle); // Assuming you've got someTitle
if (sub != null) {
   record = sub.get(someDate); // Same for someDate
   if (record != null) {
       record.updateTime(newTime);
   }
}

Map of Map equals hashCode, , Map<String, Map<Date, Record>> . O (1) . , , Title Date, , .

+3

HashSet

@Override
    public boolean equals(Object obj) {
        if(this == obj) return true;
        if(!(obj instanceof Record)) return false;
        Record otherRecord = (Record)obj;
        return (this.time.equals(otherRecord.time) && this.title.equals(otherRecord.title));
    }

    @Override
    public int hashCode() {        
        int result = titile != null ? titile.hashCode() : 0;
        result = 31 * result + (time != null ? time.hashCode() : 0);
        return result;

    }

hashset

   HashSet hset = new HashSet<Record>();
   if(!hset.add(record)){
        hset.remove(record);
        hset.add(record);
   }

HashSet , .

0

Use a map implementation that gives you access O(1), such as HashMapor ConcurrentHashMap.

pseudo-users code:

class Record {
    static class Key {
        Date date
        String title
        // proper hashCode and equals
    }
    Date date
    String title
    int id
    Time time
    Key getKey() {...}
}


Map<Record.Key, Record> recordMap = new HashMap<>();
for (record : records) {
    recordMap.merge(record.getKey(), record, 
                   (oldRecord, newRecord) -> oldRecord.setTime(newRecord.getTime()));
}
0
source

Source: https://habr.com/ru/post/1685917/


All Articles