Home > front end >  What structure to use for dynamic key sort and query?
What structure to use for dynamic key sort and query?

Time:11-04

public class Book {
    private Long id;
    private Long quantity;
}

I want a map that sort the quantity of books, but the quantity always change, how to sort this when quantity changed, be carefully quantity could be same for different books.

CodePudding user response:

I think you can use tow maps, one for storing all the books, another for sorting by quantity.

Here is the test codes:

import java.util.*;

public class Book {
    private Long id;
    private Long quantity;

    public Book(Long id, Long quantity) {
        this.id = id;
        this.quantity = quantity;
    }

    public Long getId() {
        return id;
    }

    public Long getQuantity() {
        return quantity;
    }

    @Override
    public String toString() {
        return "Book{"  
                "id="   id  
                ", quantity="   quantity  
                '}';
    }
}

class Books {
    // id -> Book
    private final Map<Long, Book> books = new HashMap<>();
    // q -> idSet
    private final SortedMap<Long, Set<Long>> sortedMap = new TreeMap<>(Comparator.reverseOrder());

    public void save(Book book) {
        Book old = books.get(book.getId());
        books.put(book.getId(), book);

        // q -> idSet
        Long q = book.getQuantity();
        Set<Long> idSet = sortedMap.get(q);
        if (null == idSet) {
            idSet = new HashSet<>();
        }
        idSet.add(book.getId());

        // sorted by quantity
        sortedMap.put(q, idSet);

        // remove id from old idSet
        if (old != null) {
            Long oq = old.getQuantity();
            if (!q.equals(oq)) {
                idSet = sortedMap.get(oq);
                idSet.remove(book.getId());
                if(idSet.isEmpty()){
                    sortedMap.remove(oq);
                }
            }
        }
    }

    public Book getBook(Long id) {
        return books.get(id);
    }

    @Override
    public String toString() {
        StringBuilder b = new StringBuilder("Books{\n");
        sortedMap.forEach((q, idSet) -> {
            b.append(String.format("           
  • Related