简体   繁体   中英

Java sort map or array

I have code:

    List<ModelMap> nameCustomer = new ArrayList<ModelMap>();

    for (int i=1;i<150;i++) {
                    ModelMap map = new ModelMap();
                    map.put("name", "nazwa " + i);
                    map.put("surname", "nazwisko " + i);
                    map.put("number", "123 ");
                    nameCustomer.add(map);
                }

            ModelMap[] result = new ModelMap[nameCustomer.size()];
            ModelMap[] rowsArray = nameCustomer.toArray(result);

How can I sort nameCustomer (or rowsArray) by surname or number?

You need to implement a Comparator that defines your sorting criteria,
then you can use Arrays.sort for arrays, or Collections.sort for Lists, or dump everything into a SortedSet (eg, TreeSet )

You can use the Collections.sort(nameCustomer, comparator) method to sort your list. For that you have to write the code for your Comparator.The code for Comparator will be -

public Comparator<ModelMap> getComparator(final String sortBy){
   if ("surname".equals(sortBy)) {
   return new Comparator<ModelMap>() {
   @Override int compare(ModelMap m1, ModelMap m2) 
    return m1.getSurname().compareTo(m2.getSurname());
   }};} 
     else if (condition) {// ...  }
      else {
        throw new IllegalArgumentException("invalid sort field '" + sortBy + "'"); }
       }

I am assuming that you have a getSurname method written in your ModelMap class to get the surname. If not then write it to make the above code work.

You can visit here for further help. Cheers !!

You'll probably want to use the Collections.Sort package. Lists maintain "natural ordering" to maintain consistency. eg

    List<Name> names = Arrays.asList(nameArray);
    Collections.sort(names);
    System.out.println(names);

using the Colections.sort() and give it a custom Comparator class implementation, which will do a string compare by surname.

Or use a LinkedHashMap, which has consistency after put() ang get() and keys sorted.

I hope it helps!

You can implement your own iterator on List, which could be parametrized to return only the inner key you specified.

Then, "iterating" with a standard sorter around it does the trick.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM