简体   繁体   中英

How to sort data in a file by name and by age - Java

I'm working on a project and have to figure out how to sort data in a file and display it by first name and age (separately, so there are 2 lists of data). I was thinking about just typing out the data into an array, but apparently the array has to pull the data from the file and then display it. It's kind of hard to explain, so here is an example:

If the data in the file is:

Bob Smith
10
Sarah
8
Mike
12
Scott Brown
14

I would have to display it so the output looks more like this:

Sorted by Age:
Scott Brown 14
Mike 12
Bob Smith 10
Sarah 8

Sorted by name:
Bob Smith 10
Mike 12
Sarah 8
Scott Brown 14

I think I have a pretty good understanding of how to write the code to sort it if it was hard coded (which I'm not allowed to hard code it unfortunately), but I'm confused how I would pull the data from the file and use that to sort it out and then display it. I started writing out a do while loop that consists of a for loop and an if statement to sort the names, but the big question is how to use the data from THAT file and display it.

Sorry if it sounds confusing, I'm so lost on this!

Consider using Collections and its sort mechanism along with various comparators. I think that's what you are looking for.

Please take a look at this post

This is actually straightforward, and you've got a couple of options.

  • Create a Person object that represents a name and age, which is also Comparable . Read your data into this entity and store it in a List . Then, sort the list with Collections.sort() . If you want to sort based on a different field, you can supply a custom Comparator to the sort method.

     public Person implements Comparable<Person> { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } // getters @Override public int compareTo(Person another) { return this.name.compareTo(another.getName()); } } 
  • Create a TreeMap<String, Integer> of entries. Read them in and you can then determine the order they're printed by supplying a custom Comparator .

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