Java - 重新排序Map <string,list <string =“”>&gt; </string,>

时间:2014-12-16 04:18:49

标签: java android arrays sorting hashmap

我有一张地图&lt;字符串,列表&lt;串GT;&GT;调用数据,看起来像这样

data = {Salad=[Salad Bar Station, Green Pepper & Tomato Salad, Lo Mein Noodle Salad], 
        Pizza=[Cheese Pizza - Slice, Pepperoni Pizza, Tomato Bruschetta Flatbread Pizza, Herb 
               Seasoned Breadsticks, Spaghetti Sauce with Tomato Bits], 
        Dessert=[Carnival Cookies, Sweet Cinnamon Brownies, Oreo Crumble Pudding Cup, 
                 Cherry Jell-O Parfait], 
        Cold Cereal=[Miscellaneous/Peripherals]}

现在我想重新排序这个看起来像这个

data = Pizza=[Cheese Pizza - Slice, Pepperoni Pizza, Tomato Bruschetta Flatbread Pizza, Herb 
               Seasoned Breadsticks, Spaghetti Sauce with Tomato Bits], 
       Salad=[Salad Bar Station, Green Pepper & Tomato Salad, Lo Mein Noodle Salad],
       Cold Cereal=[Miscellaneous/Peripherals]
       Dessert=[Carnival Cookies, Sweet Cinnamon Brownies, Oreo Crumble Pudding Cup, 
                 Cherry Jell-O Parfait]}

现在我有一些关于如何执行此操作的伪代码,但不太确定如何在代码中执行此操作。

所以我希望有一个数组,其中包含我想要的键的顺序。所以就像

String[] desiredOrder = {"Pizza","Salad","Cold Cereal"};
int destination = 0;

然后有类似

的东西
for (int i=0; i < desiredOrder.length; i++) {
     //then find if the first desiredOrder object is in the data array
         //then check if it is in the right spot
             if (it is in right spot) {
                 //do nothing
             }
             else {
                  //move it to the right spot
             }
 }

我真的很感激你可以帮助我填补其余内容,以便将键及其值移到正确的位置。

提前感谢您的帮助。

编辑

为了实现这个目的,我正在从网络解析xml,这就是我正在做的事情,请注意我刚刚将它改为LinkedHashMap,所以现在它按照xml的顺序得到它,但是我仍然希望将它重新排列为我自己的订单。

String currentDay = "";
String currentMeal = "";
String counter = "";

 LinkedHashMap<String, List<String>> itemsByCounter = new LinkedHashMap<String , List<String>>();
        List<String> items = new ArrayList<String>();
while (eventType != XmlResourceParser.END_DOCUMENT) {
            String tagName = xmlData.getName();
            blogPost = new HashMap<String, String>();

            switch (eventType) {
                case XmlResourceParser.START_TAG:
                    if (tagName.equalsIgnoreCase("day")) {
                        currentDay = xmlData.getAttributeValue(null, "name");
                    }
                    if (tagName.equalsIgnoreCase("meal")) {
                        currentMeal = xmlData.getAttributeValue(null, "name");
                    }
                    if (tagName.equalsIgnoreCase("counter") && currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal)) {
                        counter = xmlData.getAttributeValue(null, "name");
                    }

                    break;
                case XmlResourceParser.TEXT:
                    if (currentDay.equalsIgnoreCase(day) && currentMeal.equalsIgnoreCase(meal)) {
                        if (xmlData.getText().trim().length() > 0) {
                            items.add(xmlData.getText());

                        }

                    }
                    break;

                case XmlPullParser.END_TAG:
                    if (tagName.equalsIgnoreCase("counter")) {
                        if (items.size() > 0) {
                            itemsByCounter.put(counter, items);
                            items = new ArrayList<String>();
                        }
                    }
                    break;
            }
            eventType = xmlData.next();
        }

很抱歉它很长,但基本上它只是抓取项目,添加一个作为键,然后将其作为值。

以下是我使用我的数据填充ListView的方法。

MyCustomAdapter mAdapter = new MyCustomAdapter();
    for (int i = 0; i < data.size(); i++) {
        Object[] array = data.keySet().toArray();
        String string = array[i].toString();
        mAdapter.addSeparatorItem(string);
        for (int i2 = 0; i2 < data.get(string).size(); i2++) {
            mAdapter.addItem(data.get(string).get(i2));
        }

    }
public class MyCustomAdapter extends BaseAdapter{
    ArrayList mData = new ArrayList();
    LayoutInflater mLayoutInflater;

    private static final int TYPE_ITEM = 0;
    private static final int TYPE_SEPARATOR = 1;
    private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;

    private TreeSet mSeparatorsSet = new TreeSet();

    public MyCustomAdapter() {
        mLayoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public void addItem(final String item) {
        mData.add(item);
        notifyDataSetChanged();
    }

    public void addSeparatorItem(final String item) {
        mData.add(item);
        // save separator position
        mSeparatorsSet.add(mData.size() - 1);
        notifyDataSetChanged();
    }

    @Override
    public int getItemViewType(int position) {
        return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR : TYPE_ITEM;
    }

    @Override
    public int getViewTypeCount() {
        return TYPE_MAX_COUNT;
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    @Override
    public String getItem(int position) {
        return mData.get(position).toString();
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;
        int type = getItemViewType(position);
        System.out.println("getView " + position + " " + convertView + " type = " + type);
        if (convertView == null) {
            holder = new ViewHolder();
            switch (type) {
                case TYPE_ITEM:
                    convertView = mLayoutInflater.inflate(R.layout.item_cell_view, parent, false);
                    holder.textView = (TextView)convertView.findViewById(R.id.text);
                    break;
                case TYPE_SEPARATOR:
                    Context context = DiningItemsActivity.this;
                    convertView = mLayoutInflater.inflate(R.layout.header_cell_view, parent, false);
                    holder.textView = (TextView)convertView.findViewById(R.id.textSeparator);
                    convertView.setBackgroundColor(colorBar);
                    break;
            }
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }
        holder.textView.setText(mData.get(position).toString());
        return convertView;
    }

    public class ViewHolder {
        public TextView textView;
    }

2 个答案:

答案 0 :(得分:0)

我认为使用 linkedHashMap 可以解决您的问题。可以在起始时使用linkedHashMap,也可以维护订单或从其他地图填充iterate

填写myMap的伪代码

public static void main(String[] args) throws Exception {

        LinkedHashMap<String, List<String>> linkedHashMap = new LinkedHashMap<String, List<String>>();
        String[] desiredOrder = { "Pizza", "Salad", "Cold Cereal", "Dessert" };

        Map<String, List<String>> myMap = new HashMap<String, List<String>>();

        List<String> myList1 = new ArrayList<String>();
        List<String> myList2 = new ArrayList<String>();
        List<String> myList3 = new ArrayList<String>();
        List<String> myList4 = new ArrayList<String>();

        myList1.add("Salad Bar Station, Green Pepper & Tomato Salad");
        myList1.add("Lo Mein Noodle Salad");
        myMap.put("Salad", myList1);

        myList2.add("Cheese Pizza - Slice");
        myList2.add("Pepperoni Pizza");
        myList2.add("Tomato Bruschetta Flatbread Pizza");
        myList2.add("HerbSeasoned Breadsticks");
        myList2.add("Spaghetti Sauce with Tomato Bits");
        myMap.put("Pizza", myList2);

        myList3.add("Carnival Cookies");
        myList3.add("Sweet Cinnamon Brownies");
        myList3.add("Oreo Crumble Pudding Cup");
        myList3.add("Cherry Jell-O Parfait");
        myMap.put("Dessert", myList3);

        myList4.add("Miscellaneous/Peripherals");
        myMap.put("Cold Cereal", myList4);

        System.out.println(myMap);

        for (int i = 0 ; i < desiredOrder.length ; i++) {
            linkedHashMap.put(desiredOrder[i], myMap.get(desiredOrder[i]));
        }

        System.out.println("-------------------------------");
        System.out.println(linkedHashMap);
    }

<强>输出

  

{沙拉= [沙拉吧站,青椒&amp;番茄沙拉,Lo Mein面条   沙拉],甜点= [嘉年华饼干,甜肉桂布朗尼,奥利奥   Crumble Pudding Cup,Cherry Jell-O Parfait],冷   谷物= [杂项/周边],比萨= [芝士比萨 - 切片,   意大利辣香肠比萨饼,番茄意式烤面包比萨饼,HerbSeasoned   面包棒,番茄酱意大利面酱]}


  

{Pizza = [Cheese Pizza - Slice,Pepperoni Pizza,Tomato Bruschetta   大饼比萨饼,HerbSeasoned面包棒,意粉酱用蕃茄   比特],沙拉= [沙拉吧站,青椒&amp;番茄沙拉,罗米   面条沙拉],冷谷物= [杂项/外围设备],   甜点= [嘉年华饼干,甜肉桂布朗尼,奥利奥碎   布丁杯,Cherry Jell-O Parfait]}

答案 1 :(得分:0)

public class TestComparator implements Comparator<String> {
    List<String> order;
    public TestComparator(String[] desiredOrder) {
        order = Arrays.asList(desiredOrder);
    }

    public static void main(String args[]) throws InterruptedException {
        String[] desiredOrder = {"Pizza","Salad","Cold Cereal"};
        TreeMap<String, List<String>> treeMap = new TreeMap<String, List<String>>(new TestComparator(desiredOrder));

        //add into Map
    }
    @Override
    public int compare(String o1, String o2) {
        Integer index1 =order.indexOf(o1);
        Integer index2 =order.indexOf(o2);
        return index1.compareTo(index2);
    }
}