当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Multi Value Mult Priority Sort Map

问题描述:

In android, how do you sort multiple values in a single row based on priority, similar to the Sort function in Excel?

Map<String,String,Float,Integer> shoes; // Style, Color, Price, Quantity

shoes.put("Boots","Red",15.50,5);

shoes.put("Boots","Green",17.50,2);

shoes.put("Skate","Red",12.25,6);

shoes.put("Skate","Blue",13.05,9);

shoes.Sort(1,0,2,3); // sorts by color, then by style

shoes.Sort(2,0,1,3); // sorts by price, then by style

网友答案:

There's a good block of example code here that covers setting up a general comparator. To sort on multiple columns will take multiple calls, but it will have the desired effect. From the Collections spec

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

So you start with a Shoe

public class Shoe
{
  String style;
  String color;
  float price;//There are some reasons to not use float for money, google has lots of blogs etc
  int quantity;
}

Then make your comparators based on the tutorial linked above, and eventually:

ArrayList<Shoe> shoes = makeShoes();
Collections.sort(shoes,col1Comparator);
Collections.sort(shoes,col2Comparator);
Collections.sort(shoes,col3Comparator);
网友答案:

The suggestion made by Kae is correct, but, you can do something like this:

  1. Create a class (internal or not) that implements the interface Comparator and it should as the infer type related what you want to compare.
  2. Create a new TreeSet with the same specification of the Map and with the Comparator as parameter
  3. Put all objects into the created treeseet.

Look this thread: How to sort a Map<Key, Value> on the values in Java?

But again, you should think about creating an Class to your need.

[]s Neto

分享给朋友:
您可能感兴趣的文章:
随机阅读: