Ordered insertion in linkedHashSet, any performant way ?

给你一囗甜甜゛ 提交于 2019-12-02 07:01:49

问题


So I have a LinkedHashSet , with values say a1, a2, , b, c1, c2

I want to replace, b with x , such that the order of x should be same as order of b.

One obvious way would be

 private LinkedHashSet<String> orderedSubstitution(final Set<String> originalOrderedSet, final String oldItem,
            final String newItem) {
        final LinkedHashSet<String> newOrderedSet = new LinkedHashSet<String>();
        // Things we do to maintain order in a linkedHashSet
        for (final String stringItem : originalOrderedSet) {
            if (stringItem.equals(oldItem)) {
                newOrderedSet.add(newItem);
            } else {
                newOrderedSet.add(stringItem);
            }
        }
        return newOrderedSet;
    }

not only this is O(n) i also feel this is not the fastest way. Any better solution ? NOTE : I HAVE TO use linkedHashMap.


回答1:


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.




回答2:


  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.



来源:https://stackoverflow.com/questions/12826916/ordered-insertion-in-linkedhashset-any-performant-way

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