Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

In-order access to LinkedHashMap keys #1850

Closed
dmolesUC opened this issue Feb 1, 2017 · 5 comments
Closed

In-order access to LinkedHashMap keys #1850

dmolesUC opened this issue Feb 1, 2017 · 5 comments

Comments

@dmolesUC
Copy link

dmolesUC commented Feb 1, 2017

Presumably for reasons of efficiency, LinkedHashMap.keySet() returns the unordered keySet of the underlying HashMap. It would be convenient to be able to get the keys in order without having to resort to a workaround like map.iterator().map(entry -> entry._1), even if the underlying implementation isn't any less ugly than that. E.g.

/** Returns the keys contained in this map, in insertion order. */
public Queue<K> keys() {
  return list.map(entry -> entry._1);
}

(Forgive me if there's a more idiomatic way to do this; I have some Scala background but I've been stuck in Ruby for a year or two, and my Java and Javaslang are both rusty.)

@ruslansennov
Copy link
Member

We can't change LinkedHashMap::keys signature as you proposed, because it will clash with method in super interface. However we could change it to something like this

    @Override
    public Set<K> keySet() {
        return new LinkedHashSet(this);
    }

This would keep order of elements

@dmolesUC
Copy link
Author

dmolesUC commented Feb 1, 2017

That's why I suggested adding keys() rather than changing keySet(), but the LinkedHashSet idea is much, much better — I forgot that a LinkedHashSet is backed by a LinkedHashMap.

To do that, though, wouldn't you also need to change the LinkedHashSet constructor to take a LinkedHashMap<T, Object> rather than a LinkedHashMap<T, T>?

@ruslansennov
Copy link
Member

That's why I suggested adding keys() rather than changing keySet()

Oh, sorry :)

To do that, though, wouldn't you also need to change the LinkedHashSet constructor to take a LinkedHashMap<T, Object> rather than a LinkedHashMap<T, T>?

Yes, wrapped map should be changed to

private final LinkedHashMap<T, Object> map;

@ruslansennov
Copy link
Member

java.util.LinkedHashMap.keySet() also keeps order

@danieldietrich danieldietrich added this to the 2.1.0 milestone Feb 5, 2017
@danieldietrich
Copy link
Contributor

Fixed with #1854

@danieldietrich danieldietrich modified the milestones: 2.0.6, 2.1.0 Mar 15, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants