简体   繁体   中英

Sort an array of instances of a custom class based on a field

I'm having a problem right now in a project that im making just to learn more about java, so I have a txt file wich has wonders, i'll have to read it and then store it different information in a object (name country, heightdepth, acessbility, hostility, kmfromlondon, temperature, wondervalue and a fact about the wonder), then I have to sort by the hostility rate and output the all of the wonders

heres the txt file of the wonders:

Amazonia,Brazil,60,10,10,8100,30,4,The Amazon rainforest occupies some 5.5 million square kilometres of South America.
Iguassu Falls,Brazil|Argentina,82,11,50,10064,25,4,Two hundred and seventy waterfalls flow along nearly 3 kilometres of rivers.
Niagra Falls,USA|Canada,50,18,69,5804,20,4,Adventurous tourists can take a cruise on the river below into the falls' mist.
Giant's Causeway,Northern Ireland,12,19,17,592,15,2,Legend has it that is is a former 'walkway' to Scotland.
Great Barrier Reef,Australia,60,10,10,15292,28,4,Over 30 species of whale and 15000 species of fish live here.
Mount Everest,Tibet|Nepal,8840,7,95,7424,-10,4,The highest mountain on Earth is located in the Himalayas.
Mount Vesuvius,Italy,1281,18,95,1630,30,1,The only volcano in mainland Europe to have erupted in the last 100 years.
Old Faithful,USA,55,14,65,7432,118,2,Over half of the world's geysers are located in Yellowstone national park.
Sahara Desert,African Union,3445,14,84,3800,35,3,Covers part of North Africa and is almost the same size as the USA.
Great Rift Valley,African Union,1470,14,12,5887,25,4,The valley was formed by activity between tectonic plates 35 million years ago.
Gobi Desert,Mongolia|China,2700,9,84,7279,30,3,The desert has been the location of many fossil finds.
Ngorongoro Crater,Tanzania,610,14,19,5804,30,2,Home to almost 25000 animals including masses of flamingoes around Lake Magadi.
Perito Morena Glacier,Argentina,60,9,82,13230,-5,3,The 5 kilometre wide glacier is well known for its process of rupturing.
Mount Fuji,Japan,3776,13,69,8671,25,2,Although classed as active its last eruption was in 1707.
Mont Blanc,Italy|France,4808,18,85,808,0,2,The highest mountain in Europe and a popular skiing destination.
The Dead Sea,Israel|Jordan,418,13,91,3666,25,1,The lowest point on the surface of the Earth and is really two large lakes.
The Matterhorn,France|Italy|Switzerland,4478,17,85,840,-5,2,Not the highest mountain in the Alps but perhaps the most breathtaking.
Uluru,Australia,346,10,70,14993,35,4,A massive monolith made from sandstone infused with minerals that reflect in the sunlight.
Lake Baikal,Russia,1637,8,55,6613,-30,2,An immense depth of 1637 metres and contains 20% of the worlds fresh water.
Kilauea,The Hawaiian Islands,1247,9,65,11783,30,3,Hawaiian legend considers the island to be the home of a volcano goddess.
Guilin Caves,China,220,9,16,9101,30,2,The people of Guilin have had to take refuge in them during times of conflict.
Giant Sequoia,USA,84,15,2,8570,30,2,The largest species of tree found only in California.
Mount Erebus,Antarctica,3794,4,95,17059,-49,3,Has continually erupted since 1972 and has a permanent lava lake within its summit.
Grand Canyon,USA,1600,15,80,8296,30,4,A vast and breathtaking spectacle stretching across the Arizona desert.

so I created an object like this

public class Wonders {
    String name;
    List countries = new ArrayList();
    int heightDepth;
    int accessibility;
    int hostility;
    int kmFromLondon;
    int temperature;
    int wonderValue;
    String fact;
    List compare = new ArrayList();

and then I stored it like this

     String unftxt[];
        unftxt = new String[24];
        Wonders w[] = new Wonders[unftxt.length];



        try (Scanner sfile = new Scanner(new File(fName))) {

           while(sfile.hasNextLine()){
               unftxt[ctrl] = sfile.nextLine();
               ctrl++;
           }//end while .hasnextLine()
        }//try

        for(int i=0;i<unftxt.length;i++){
            String[] parts = unftxt[i].split(",");
            w[i] = new Wonders();
            w[i].name = parts[0];
            w[i].countries.add(Arrays.toString(parts[1].split("\\|")));
            w[i].heightDepth = Integer.parseInt(parts[2]);
            w[i].accessibility = Integer.parseInt(parts[3]);
            w[i].hostility = Integer.parseInt(parts[4]);
            w[i].kmFromLondon = Integer.parseInt(parts[5]);
            w[i].temperature = Integer.parseInt(parts[6]);
            w[i].wonderValue = Integer.parseInt(parts[7]);
            w[i].fact = parts[8];

        }

im new in programming and i've been stuck for a while now so my question is how can I sort this array by hostility

The regular way to define a custom ordering in Java is via a Comparator instance. This object can be plugged into the sorting routines of eg Arrays or Collections .

In Java 8 for example you can sort your array like so:

Arrays.sort(wonderArray, Comparator.comparingInt(wonder -> wonder.hospitality));

In Java 7 or before, you can do it with an anonymous class:

Arrays.sort(wonderArray, new Comparator<Wonder>() {
  @Override public int compareTo(Wonder w1, Wonder w2) {
    return Integer.compare(w1.hospitality, w2.hospitality);
  }
});

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