0

I have following code:

users.stream()
                .sorted((u1, u2) -> u2.getScore().compareTo(u1.getScore()))
                .limit(count)
                .collect(Collectors.toMap((User::getName), (User::getScore)));

Content of result is right but when I want to foreach it - it output in unpredictable result. I think it is because under the hood HashMap is used.

Is there way to collect to mp with predictable result?

gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • 1
    Use `toMap(Function super T,? extends K> keyMapper, Function super T,? extends U> valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier)`, and make the merge function throw an exception if it didn't suppose to happen. – Alexis C. Oct 03 '15 at 12:50
  • @Alexis C. I should not provide merge function. I have unique names – gstackoverflow Oct 03 '15 at 12:51
  • 2
    That's why I said to throw an exception in the merge function. – Alexis C. Oct 03 '15 at 12:52

1 Answers1

0

This works:

           return users.stream()
            .sorted((u1, u2) -> u2.getScore().compareTo(u1.getScore()))
            .limit(count)
            .collect(Collectors.toMap((User::getName), (User::getScore), (k, v) -> {
                        throw new RuntimeException(String.format("Duplicate key %s", k));
                    },
                    LinkedHashMap::new));
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710