0

I want to get a sorted List of my Products. The list should be Sorted by the attribute postition, which is located in the PafElement class. it is an Integer. I started to sort the product list in the method "getSortedList" I've tested the method with four objects. the objects one and two, are switched. This means object one is at position 2 in the HashMap and object two is at Position one. the other objects are fine.

Apparently the HashMap does not put new elements at the end of the map. I want to know, if there is a possibility to achieve this.

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;
}
Firesnake
  • 5
  • 3

1 Answers1

0

HashMap works by overriding equals and hashcode in the Class of which you want to put objects in your map. HashMap is fast and can take out an object with const complexity, they are ALWAYS unordered.

What you obviously need is a TreeMap. TreeMap is a Sorted Key-Value List. Your Class needs to implement Comparable and you have to write your logic for comparison of your products or you can use Comparator which you will put in your TreeMap. TreeMapDifference between HashMap and TreeMap well explained

Community
  • 1
  • 1
T.Dimitrov
  • 157
  • 2
  • 7