code: public static int[] compact (int[] list)
      {
          int llength = list.length, lcount = 0;
          // count up the non-zero entries
          for (int i = 0; i < llength; i++) {
              if (list[i] != 0) {
                  lcount++;
              }
          }
  
          int[] nlist = new int[lcount];
          int n = 0;
          for (int i = 0; i < llength; i++) {
              if (list[i] != 0) {
                  nlist[n++] = list[i];
              }
          }
  
          return nlist;
      }
docs: Converts a sparse array (with zero-valued entries) into a compact
  array (where all elements contain non-zero values) with ordering
  preserved.