当Value为Object时,按属性对hashMap进行排序

时间:2017-02-14 00:14:18

标签: java android sorting hashmap

我想获得一份已排序的产品清单。 该列表应按属性postition排序,该属性位于PafElement类中。它是一个整数。 我开始在方法" getSortedList"中对产品列表进行排序。 我用四个对象测试了这个方法。切换对象一和二。这意味着对象1位于HashMap中的位置2,而对象2位于位置1。其他对象都很好。

显然,HashMap不会在地图的末尾添加新元素。我想知道,如果有可能实现这一点。

public Product(){}

public Product(Init activity){
    final Init init = activity;
    Log.i("PRODUCT","Costruct");
    // TODO: 12.02.2017 use own logger class
    TextView productName = (TextView)activity.findViewById(R.id.productName);

    TextView.OnEditorActionListener listener = new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (event != null) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    Long milis = System.currentTimeMillis();
                    setId(milis);
                    setName(v.getText().toString());
                    setPosition(getNextPosition());
                    create(init);
                    v.setText("");
                    v.setVisibility(View.GONE);
                    // TODO: 08.02.2017 log successful creation;
                    return true;
                }
            }
            return false;
        }

    };

    productName.setOnEditorActionListener(listener);
    productName.setVisibility(View.VISIBLE);
}

public static void toList(Product p){
    productList.put(p.getId(),p);
}

public static void initialise(Element products){
    NodeList productList = products.getChildNodes();
    for(int i = 0; i < productList.getLength(); i++){
        Node product = productList.item(i);
        if(product.getNodeName().equals("product")) {
            Element productElement = (Element) product;
            String id = productElement.getAttribute("productId");
            Integer pos = Integer.parseInt(productElement.getAttribute("position"));
            String name = productElement.getElementsByTagName("name").item(0).getTextContent();
            Product p = new Product();
            p.setName(name);
            p.setId(Long.parseLong(id));
            p.setPosition(pos);
            updatePosition(pos);
            Product.toList(p);
        }
    }
}

public static HashMap<String,Product> getList(){
    return productList;
}

public static HashMap<String,Product> getSortedList(){
    HashMap<String,Product> productList = Product.getList();
    HashMap<String,Product> sortedList = new HashMap<String, Product>();
    int[] positions = new int[productList.size()];
    int i = 0;
    for(String id :productList.keySet()){
        Product p = productList.get(id);
        positions[i] = p.getPosition();
        i++;
    }

    Arrays.sort(positions);
    while(sortedList.size() < productList.size()) {
        for (Integer position : positions) {
            for (String id : productList.keySet()){
                Product p = productList.get(id);
                if (p.getPosition().equals(position)) {
                    sortedList.put(id, p);
                }
            }
        }
    }
    return sortedList;
}

public static Product[] getListAsArray(){
    Product[] p = new Product[productList.size()];
    int i = 0;
    for(Product product : productList.values()){
        p[i] = product;
        i++;
    }
    return p;
}

private void create(Init init){
    try {
        DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
        domFactory.setIgnoringComments(true);
        DocumentBuilder builder = domFactory.newDocumentBuilder();
        Document store = builder.parse(new File(init.PATH));
        Element pl = store.getElementById("productList");
        Element product = store.createElement("product");
        Text name = store.createTextNode(this.name);
        Text id = store.createTextNode(this.id + "");
        Element productName = store.createElement("name");
        productName.appendChild(name);
        product.setAttribute("productId",(this.id + ""));
        product.setIdAttribute("productId",true);
        product.setAttribute("position",this.position + "");
        product.appendChild(productName);
        pl.appendChild(product);

        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer t = tf.newTransformer();
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        DOMSource domSource = new DOMSource(store);
        StreamResult sr = new StreamResult(new File(init.PATH));
        t.transform(domSource,sr);
        Log.i("PRODUCT","created");

        Product.toList(this);
        /**
         * @Important the string in index of has to be the same as one of the headres in class Init.java
         * */
        init.getListAdapter().update("PafElements",this.getName());

    }catch(ParserConfigurationException | TransformerException | SAXException | IOException e){
        e.printStackTrace();
        // TODO: 08.02.2017 use own logger class
    }
}

private static void updatePosition(Integer current){
    if(maxPostition != null) {
        if (current > maxPostition) {
            maxPostition = current;
        }
    }else{
        maxPostition = current;
    }
}

private static Integer getNextPosition(){
    Integer pos = maxPostition;
    if(pos == null){
        pos = 1;
    }else{
        pos += 1;
    }
    maxPostition = pos;
    return pos;
}

1 个答案:

答案 0 :(得分:0)

HashMap通过覆盖要在地图中放置对象的Class中的equals和hashcode来工作。 HashMap很快,并且可以取出具有const复杂性的对象,它们始终是无序的。

你显然需要的是TreeMap。 TreeMap是一个排序键值列表。 您的类需要实现Comparable,您必须编写逻辑以比较您的产品,或者您可以使用将放在TreeMap中的Comparator。 TreeMap Difference between HashMap and TreeMap well explained