code: public static AbstractMolecule mergeRgroups(AbstractMolecule molecule) throws BuilderMoleculeException, ChemistryException {
      try {
        boolean flag = true;
        // while (flag) {
        // if (molecule.getAttachments().size() > 0) {
        for (int i = molecule.getAttachments().size() - 1; i > -1; i--) {
          org.helm.chemtoolkit.Attachment attachment = molecule.getAttachments().get(i);
          int groupId = AbstractMolecule.getIdFromLabel(attachment.getLabel());
          AbstractMolecule rMol = Chemistry.getInstance().getManipulator().getMolecule(attachment.getSmiles(), null);
          molecule = Chemistry.getInstance().getManipulator().merge(molecule, molecule.getRGroupAtom(groupId, true), rMol, rMol.getRGroupAtom(groupId, true));
        } 
        return molecule;
      } catch (NullPointerException | IOException | CTKException e) {
        throw new BuilderMoleculeException("Unused rgroups can't be merged into the molecule" + e.getMessage());
      }
    }
docs: method to merge all unused rgroups into a molecule
  
  @param molecule input molecule
  @return molecule with all merged unused rgroups
  @throws BuilderMoleculeException if the molecule can't be built
  @throws ChemistryException if the Chemistry Engine ca not be initialized