Given a Map return the entries in the Map in the passed in List in order. - Java java.util

Java examples for java.util:Map Key

Description

Given a Map return the entries in the Map in the passed in List in order.

Demo Code

/*/* w w  w .ja  v  a  2 s.  c  om*/
 * Copyright 2006 - Gary Bentley
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
//package com.java2s;
import java.util.Map;
import java.util.List;

import java.util.Arrays;

public class Main {
    /**
     * Given a Map return the entries in the Map in the passed in
     * List in order.
     *
     * @param map The Map to use.
     * @param list The List to fill up.
     */
    public static void getMapEntriesAsOrderedList(Map map, List list) {

        // Get all the keys from the Map as an Array.
        Object[] keys = map.keySet().toArray();

        // Do a natural sort.
        Arrays.sort(keys);

        // Cycle over them and pull out the associated value
        // from the Map placing it into the List.
        for (int i = 0; i < keys.length; i++) {

            list.add(map.get(keys[i]));

        }

    }
}

Related Tutorials