1

my first post here & I'm only starting to learn Java so please bear with me.

I have a HashMap which stores a key and an instance of a class as the corresponding value (from a class I called Main). The object has a two variables. What I'd like to do is to get a print out based on a particular object variable, in this example by year. Here is my code:

public class Main {

    private String name;
    private int year;

    public Main(String name, int year) {
        this.name = name;
        this.year = year;
    }

protected static Map<Integer, Main> input = new LinkedHashMap<Integer, Main>();

input.put(1, new Main("Chris", 1980);
input.put(2, new Main("Daphne", 1981);
input.put(3, new Main("Sandra", 1976);
input.put(4, new Main("Adele", 1980);

So now what I'd like to be able to do is to list everyone by year. So my expected output would look like this:

1976: Sandra
1980: Chris, Adele
1981: Daphne

Many thanks

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
  • You'll need to write a sorting function. This: [Stack Overflow Question](http://stackoverflow.com/questions/780541/how-to-sort-a-hashmap-in-java) might be helpful. – M_J Apr 10 '17 at 23:28
  • You have two choices. Use a for loop, or use a stream. You will be able to find many examples if you google "stream hashmap group by", – Nick Ziebert Apr 10 '17 at 23:37
  • Thanks @NickZiebert, can you please show me how I'd use a loop? –  Apr 10 '17 at 23:43
  • 1
    I would definitely use streams for this. – Nick Ziebert Apr 10 '17 at 23:46
  • Oh OK, would you be able to provide an example? –  Apr 10 '17 at 23:47

2 Answers2

2

One way to do it is to use a stream, for example:

Map<Integer,List<Main>> mainByYear = input.values().stream().collect(Collectors.groupingBy
    (e -> e.year));

Then you can iterate through the mainByYear map to print out the key, and the associated list members.

jjcipher
  • 147
  • 1
  • 2
  • 7
0

Using streams you can do:

public class Main {
private String name;
private int year;

public Main(String name, int year) {
    this.name = name;
    this.year = year;
}

public String getName() {
    return name;
}

public int getYear() {
    return year;
}

public static void main(String[] args) {
    Map<Integer, Main> input = new LinkedHashMap<>();

    input.put(1, new Main("Chris", 1980));
    input.put(2, new Main("Daphne", 1981));
    input.put(3, new Main("Sandra", 1976));
    input.put(4, new Main("Adele", 1980));

    input.entrySet().stream().map(Map.Entry::getValue)
            .collect(Collectors.groupingBy(Main::getYear))
            .forEach((key, value) -> System.out.println(
                    key + ": " + String.join(", ", value.stream().map(Main::getName)
                            .collect(Collectors.toList()))));
}
}