title: Sorting Data for Firebase Realtime (Number)
body: <p>I want to sort data as 1-2-3-4-5 in Firebase Realtime. If the 3rd data is deleted, I need the new data to be added as 3. It's pretty easy to do this in mysql, but I'm having trouble finding a method for it in firebase. With the code below, I count the data and do this process, but it downloads too much and is costly.</p>
  <p>Is there a less costly way to do this?</p>
  <p>With this code I calculate which number to add. Then I pass this to the kontrol integer.</p>
  <pre><code>private void setNextKontrol(){
      kontrolLst = removeDuplicates(kontrolLst);
      Collections.sort(kontrolLst);
  
      kontrol = 1;
  
      for(int index=0;index&lt;kontrolLst.size();index++){
          if(kontrolLst.get(index)!=index+1){
              kontrol=index+1;
  
              return;
          }
      }
      kontrol=kontrolLst.size()+1;
  }
  
  public static &lt;T&gt; ArrayList&lt;T&gt; removeDuplicates(ArrayList&lt;T&gt; list)
  {
      ArrayList&lt;T&gt; newList = new ArrayList&lt;T&gt;();
  
      for (T element : list) {
  
          if (!newList.contains(element)) {
  
              newList.add(element);
          }
      }
  
      return newList;
  }
  </code></pre>
  <p>Here I am downloading all the controldata data.</p>
  <pre><code>mDatabaseReference.child(&quot;/controldata/&quot;).addValueEventListener(new ValueEventListener() {
          @Override
          public void onDataChange(DataSnapshot snapshot) {
              if (snapshot.exists()) {
                  for (DataSnapshot snap : snapshot.getChildren()) {
                      b ne = snap.getValue(b.class);
                      kontrolLst.add(ne.kontrol);
  
                  }
              }
  
          }
  
          @Override
          public void onCancelled(DatabaseError databaseError) {
          }
      });
              
                  
  </code></pre>
  <p>When a data is inserted, I insert it into controldata as kontrol:1.</p>
  <pre><code>mDatabaseReference.child(&quot;/controldata/&quot;).child(key).child(&quot;kontrol&quot;).setValue(kontrol);
  </code></pre>
  <p>End</p>
  <pre><code>class b{
      public Integer kontrol;
      public String id;
      public void setIds(String id){
          this.id = id;
      }
      public b(){}
  }
  </code></pre>