Ordered insertion in linkedHashSet, any performant way ?

折月煮酒 提交于 2019-12-02 04:08:05

One way to do it would be to use a subclass of LinkedHashSet that has the replacement built in, e.g.:

public class ReplacingLinkedHashSet extends LinkedHashSet<String> {
    private final String what;
    private final String with;

    public ReplacingLinkedHashSet(String what, String with) {
        this.what = what;
        this.with = with;
    }

    @Override
    public Iterator<String> iterator() {
        final Iterator<String> iterator = super.iterator();
        return new Iterator<String>() {
            @Override
            public boolean hasNext() {
                return iterator.hasNext();
            }

            @Override
            public String next() {
                String next = iterator.next();
                return what.equals(next) ? with : next;
            }

            @Override
            public void remove() {
                iterator.remove();
            }
        };
    }
}

But that means the replacement would have to be known before you fill the Set. (Of course you could easily turn this <String> version into a generic one.


Responding to comments:

OK, then there is no way to solve it without a full iteration. You could however just leave the LinkedHashSet untouched and decorate the iterator when retrieving the values.

  1. Create a structure Map
  2. Insert all the string with < String, OrderOfTheString>
  3. Do the insertion of the new String by adding a small Delta after the current string's OrderOfTheString.
  4. Convert Map to LikedHashSet

I know it is complicated but it is definately better when we have linked hash Map of ~1000000 elements and there are about 1000 elements to be inserted.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!