0

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!

Community
  • 1
  • 1
robguy22
  • 1
  • 2
  • 2
    Where exactly are you struck??? Are you not able to read the data from file??? Are you not able to put the data to the array??? or something else?? – Codebender Jul 03 '15 at 18:11
  • Sorry for the late reply! I'm stuck on putting the data from the file to an array and then displaying that data in alphabetical/numerical order. – robguy22 Jul 03 '15 at 23:53

2 Answers2

1

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

Community
  • 1
  • 1
Alp
  • 3,027
  • 1
  • 13
  • 28
0

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.

Makoto
  • 104,088
  • 27
  • 192
  • 230