Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

59
LINES

< > BotCompany Repo | #1034675 // OrderedMultiIterator

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (5469L/30K).

sclass OrderedMultiIterator<A extends Comparable<A>> extends ItIt<A> {
  srecord noeq Stream<A extends Comparable<A>>(Iterator<A> iterator, A element) is Comparable<Stream<A>> {
    public int compareTo(Stream<A> stream) {
      ret element.compareTo(stream.element);
    }
    
    bool advance() {
      if (!iterator.hasNext()) false;
      element = iterator.next();
      true;
    }
  }
  
  new ArrayList<Stream<A>> streams;
  bool sorted;
  
  void add(Iterable<A> it) {
    add(iteratorOrNull(it));
  }
  
  void add(Iterator<A> iterator) {
    if (iterator == null || !iterator.hasNext()) ret;
    A element = iterator.next();
    streams.add(new Stream<A>(iterator, element));
    sorted = false;
  }
  
  void addAll(Iterable<? extends Iterator<A>> iterators) {
    fOr (it : iterators) add(it);
  }
  
  public bool hasNext() {
    ret nempty(streams);
  }
  
  public A next() {
    if (!sorted) {
      sortInPlace(streams);
      set sorted;
    }
    
    var stream = first(streams);
    A element = stream.element;
    
    if (!stream.advance())
      streams.remove(0);
    else {
      // put stream in the right place
      
      int i = 0, n = streams.size()-1;
      Stream<A> stream2;
      while (i < n && stream.compareTo(stream2 = streams.get(i+1)) >= 0)
        streams.set(i++, stream2);
      streams.set(i, stream);
    }
      
    ret element;
  }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 4 computer(s): bhatertpkbcr, ekrmjmnbrukm, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1034675
Snippet name: OrderedMultiIterator
Eternal ID of this version: #1034675/8
Text MD5: 2dcf2978fc88b92fae975fb9fdf780dc
Transpilation MD5: 899e49dc2a90fcb752bf2393348a8590
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-03-01 20:13:51
Source code size: 1443 bytes / 59 lines
Pitched / IR pitched: No / No
Views / Downloads: 141 / 254
Version history: 7 change(s)
Referenced in: #1003674 - Standard Classes + Interfaces (LIVE continued in #1034167)
#1034678 - OrderedMultiIterator [backup using TreeSet, works but is slow]