java - Compare and sort String which have number and special characters -


i have list of string need sort (see below).

  • "< 5 ha"
  • ">= 10 ha < 20 ha"
  • ">= 20 ha < 50 ha"
  • ">= 5 ha < 10 ha"
  • ">= 50 ha"

looks simple until now, didn't find easy way it. element class have property of type string named code. java code below, idea ?

    public class sortinglistcomparator {       private static list<element> testlist;        public static void main(string[] args) {          initlist();          collections.sort(testlist, new elementcomparator());           (element elem : testlist) {             system.out.println("code of element : " + elem.getcode());          }       }      private static void initlist() {         testlist = new arraylist<element>();          element elem1 = new element("< 5 ha");         element elem2 = new element(">= 10 ha < 20 ha");         element elem3 = new element(">= 20 ha < 50 ha");         element elem4 = new element(">= 5 ha < 10 ha");         element elem5 = new element(">= 50 ha");          testlist.add(elem1);         testlist.add(elem2);         testlist.add(elem3);         testlist.add(elem4);         testlist.add(elem5);     }      public static class elementcomparator implements comparator<element> {         @override         public int compare(element o1, element o2) {             return o1.getcode().compareto(o2.getcode());         }        }       } 

the real answer here: step - create helpful abstractions.

you should not @ problems "string" sorting. see, these strings represent interval (or range) information.

meaning: although might "more work" should consider modeling these aspects. in other words:

  • create class represents (mathematical) intervals
  • create code parses string " < 5 ha" interval object
  • then sort interval objects

instead of creating own class, might 3rd party libraries, outlined here.

the point is: strings contain very special information. , whole idea of oop represent "the best way" within code base.


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -