Collection with natural order and update of elements under certain conditions

0 votes
asked Aug 23, 2014 by dierre

my use case is the following:

I have certain element that I would like to insert using natural order (in my case let's say is a list of prices starting from the cheaper).

The objects I have to store follows this class:

class Article { int id; int price; }
  • I want to update the item in the Collection only if the price follows certain conditions.
  • I would like also to keep elements ordered according to price.

I was thinking of a TreeSet but the Set doesn't have a get method so updating an element, in my experience, would require to iterate the Set to find the right object.

Right now I opted for a List that I order when needed, but I'm quite curious if you think there is Collection that can fullfill my requirements or if there is a better approach.

Thanks

1 Answer

0 votes
answered Aug 23, 2014 by f-p

If I understand your question correctly, basically you just want your elements to follow an order : You can use combination of Collections.sort() and a class which implementing Comparator<E>.

  import java.util.*;

 // class used to compare "price"
class priceComparator implements Comparator<Article> {

@Override
public int compare(Article o1, Article o2) {
    return o1.price - o2.price;    
  } 
 }

  public class Article {

  int id;
  int price;

  public Article(int id, int price) {
    this.id = id;
    this.price = price;
}

public static void main(String[] args) {

    List<Article> list = new ArrayList<>();
     list.add(new Article(1, 4000));
     list.add(new Article(2, 7000)); 
     list.add(new Article(3, 1000)); 

        // sorting Article based on "price" ASCENDING
        Collections.sort(list, new priceComparator());

        // sorting Article based on "price" DESCENDING
       //Collections.sort(list, Collections.reverseOrder(new priceComparator()));

       // put the sorted pair of "id" and "price" into map
       Map<Integer,Integer> map = new LinkedHashMap<>();

      for(Article l : list){
      map.put(l.id, l.price);  
      }


    System.out.println("Id | Price");
    for(Map.Entry<Integer,Integer> elemenOfMap: map.entrySet()){
    System.out.println(elemenOfMap.getKey() +" | "+elemenOfMap.getValue());
    }       
   }
}

The output :

Id | Price
3 | 1000
1 | 4000
2 | 7000
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...