Senior
Which collection to use for a results table sorted by last name and searchable by key?
sobes.tech AI
Answer from AI
For a results table sorted by last name and searchable by key in Java, it is convenient to use a collection that provides fast search and sorting.
It is recommended to use TreeMap or TreeSet with a comparator based on the last name if the key is the last name. Collection methods can be used for searching by key.
If you need to store records with a key and value, where the key is the last name and the value is an object with data, then:
TreeMap<String, Record> records = new TreeMap<>(Comparator.naturalOrder());
// Adding
records.put("Ivanov", new Record(...));
// Searching
Record r = records.get("Ivanov");
// Iterating in sorted order
for (Map.Entry<String, Record> entry : records.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
If the last name is not unique, you can use a TreeSet with a comparator that considers the last name and other fields, or a List with subsequent sorting and filtering.