auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void run() { try { <START> String hostName = System.getProperty("fake.host"); <END> if (hostName == null) { hostName = "localhost"; } log.debug("Opening a Stomp server " + hostName + ":" + jsonPort); Reactor reactor; if (!encrypted) { reactor = ReactorFactory.getReactor(null, ReactorType.STOMP); } else { reactor = ReactorFactory.getReactor(new FakeVDSMSSLProvider(System.getProperty("fake.keystore"), System.getProperty("fake.truststore"), "changeit", null), ReactorType.STOMP); } final Future<ReactorListener> futureListener = reactor.createListener(hostName, jsonPort, new ReactorListener.EventListener() { @Override public void onAcccept(final ReactorClient client) { client.addEventListener(new MessageListener() { @Override public void onMessageReceived(byte[] message) { MessageHandler handler = new MessageHandler(client, message); service.submit(handler); } }); } }); listener = futureListener.get(TIMEOUT, TimeUnit.MILLISECONDS); } catch (Exception e) { log.error("Failure to start json server socket", e); } }</code><technical_language>Please stop system properties. need configuration in single place</technical_language>

Target:
public void run() { try { String hostName = appConfig.getJsonHost(); if (appConfig.getJsonHost() == null) { hostName = "localhost"; } log.debug("Opening a Stomp server " + hostName + ":" + jsonPort); Reactor reactor; if (!encrypted) { reactor = ReactorFactory.getReactor(null, ReactorType.STOMP); } else { reactor = ReactorFactory.getReactor(new FakeVDSMSSLProvider(System.getProperty("fake.keystore"), System.getProperty("fake.truststore"), "changeit", null), ReactorType.STOMP); } final Future<ReactorListener> futureListener = reactor.createListener(hostName, jsonPort, new ReactorListener.EventListener() { @Override public void onAcccept(final ReactorClient client) { client.addEventListener(new MessageListener() { @Override public void onMessageReceived(byte[] message) { MessageHandler handler = new MessageHandler(client, message); service.submit(handler); } }); } }); listener = futureListener.get(TIMEOUT, TimeUnit.MILLISECONDS); log.info("vdsmfake initialized"); } catch (Exception e) { log.error("Failure to start json server socket", e); } }
Source:
<code>public Response add(Host host) { <START> validateEnums(Host.class, host); <END> validateParameters(host, "name", "address", "rootPassword"); VdsStatic staticHost = getMapper(Host.class, VdsStatic.class).map(host, null); staticHost.setVdsGroupId(getClusterId(host)); AddVdsActionParameters addParams = new AddVdsActionParameters(staticHost, host.getRootPassword()); if (host.isSetOverrideIptables()) { addParams.setOverrideFirewall(host.isOverrideIptables()); } if (host.isSetRebootAfterInstallation()) { addParams.setRebootAfterInstallation(host.isRebootAfterInstallation()); } if (host.isSetSsh()) { if (host.getSsh().isSetUser()) { if (host.getSsh().getUser().isSetPassword()) { addParams.setRootPassword(host.getSsh().getUser().getPassword()); } } if (host.getSsh().isSetPort()) { addParams.getvds().setSshPort(host.getSsh().getPort().intValue()); } if (host.getSsh().isSetFingerprint()) { addParams.getvds().setSshKeyFingerprint(host.getSsh().getFingerprint()); } if (host.getSsh().isSetAuthenticationType()) { addParams.setAuthMethod(mapAuth(host.getSsh().getAuthenticationType().getAuthenticationType())); } } return performCreate(VdcActionType.AddVds, addParams, new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, IdQueryParameters.class)); }</code><technical_language>validateEnums(Host.class, host); validate AuthenticationType for</technical_language>

Target:
public Response add(Host host) { validateEnums(Host.class, host); validateParameters(host, "name", "address", "rootPassword"); VdsStatic staticHost = getMapper(Host.class, VdsStatic.class).map(host, null); staticHost.setVdsGroupId(getClusterId(host)); AddVdsActionParameters addParams = new AddVdsActionParameters(staticHost, host.getRootPassword()); if (host.isSetOverrideIptables()) { addParams.setOverrideFirewall(host.isOverrideIptables()); } if (host.isSetRebootAfterInstallation()) { addParams.setRebootAfterInstallation(host.isRebootAfterInstallation()); } if (host.isSetSsh()) { if (host.getSsh().isSetUser()) { if (host.getSsh().getUser().isSetPassword()) { addParams.setRootPassword(host.getSsh().getUser().getPassword()); } } if (host.getSsh().isSetPort()) { addParams.getvds().setSshPort(host.getSsh().getPort().intValue()); } if (host.getSsh().isSetFingerprint()) { addParams.getvds().setSshKeyFingerprint(host.getSsh().getFingerprint()); } if (host.getSsh().isSetAuthenticationMethod()) { AuthenticationMethod m = getMapper(String.class, AuthenticationMethod.class). map(host.getSsh().getAuthenticationMethod(), null); if (m != null) { addParams.setAuthMethod( getMapper(AuthenticationMethod.class, org.ovirt.engine.core.common.action.VdsOperationActionParameters.AuthenticationMethod.class).map(m, null)); } } } return performCreate(VdcActionType.AddVds, addParams, new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, IdQueryParameters.class)); }
Source:
<code>void removeCurCompactionLog() { synchronized (compactionLogLock) { if (compactionLogChannel != null) { if (!compactionLogChannel.getLogFile().delete()) { LOG.warn("Could not delete compaction log file {}", compactionLogChannel.getLogFile()); } try { compactionLogChannel.close(); } catch (IOException e) { LOG.error("Failed to close file channel for compaction log {}: {}", compactionLogChannel.getLogId(), <START> e.getMessage()); <END> } compactionLogChannel = null; } } }</code><technical_language>instead of logging exception message, log complete exception, right? get complete call stack trace aswell LOG.error("Failed close file channel for compaction log {}", compactionLogChannel.getLogId(), e);</technical_language>

Target:
void removeCurCompactionLog() { synchronized (compactionLogLock) { if (compactionLogChannel != null) { if (!compactionLogChannel.getLogFile().delete()) { LOG.warn("Could not delete compaction log file {}", compactionLogChannel.getLogFile()); } try { compactionLogChannel.close(); } catch (IOException e) { LOG.error("Failed to close file channel for compaction log {}", compactionLogChannel.getLogId(), e); } compactionLogChannel = null; } } }
Source:
<code>public String toString() { String result = ""; for (Id id : internalMap().keySet()) { result = result + ", " + "{" + id + "; " + internalMap().get(id).syncState() + "}"; } <START> return result.substring(2); <END> }</code><technical_language>string</technical_language>

Target:
public String toString() { String result = ""; String delimiter = ", "; for (Id id : internalMap().keySet()) { result = result + delimiter + "{" + id + "; " + internalMap().get(id).syncState() + "}"; } return result.substring(delimiter.length()); }
Source:
<code>public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); startSyncFolderOperation(directory, false); MenuItem menuItem = mOptionsMenu.findItem(R.id.action_switch_view); changeGridIcon(); <START> if (DisplayUtils.isGridView(directory, getStorageManager())){ <END> switchToGridView(); } else { switchToListView(); } }</code><technical_language>code fragment line 325ff</technical_language>

Target:
public void onBrowsedDownTo(OCFile directory) { setFile(directory); cleanSecondFragment(); startSyncFolderOperation(directory, false); }
Source:
<code>public void visitAnyBlock(Block block) { this.block = block; if (block instanceof ThenBlock) return; DeepBlockRewriter deep = new DeepBlockRewriter(this); deep.visit(block); <START> methodHasCondition |= deep.isDeepConditionFound() || deep.isGroupConditionFound(); <END> }</code><technical_language>isDeepConditionFound suffice is case this is false isGroupConditionFound is true</technical_language>

Target:
public void visitAnyBlock(Block block) { this.block = block; if (block instanceof ThenBlock) return; DeepBlockRewriter deep = new DeepBlockRewriter(this); deep.visit(block); methodHasCondition |= deep.isConditionFound(); methodHasDeepNonGroupedCondition |= deep.isDeepNonGroupedConditionFound(); }
Source:
<code>protected Node visitShowTables(ShowTables showTables, Void context) { CatalogSchemaName schema = createCatalogSchemaName(session, showTables, showTables.getSchema()); accessControl.checkCanShowTablesMetadata(session.getRequiredTransactionId(), session.getIdentity(), schema); if (!metadata.catalogExists(session, schema.getCatalogName())) { throw new SemanticException(MISSING_CATALOG, showTables, "Catalog '%s' does not exist", schema.getCatalogName()); } if (!metadata.schemaExists(session, schema)) { throw new SemanticException(MISSING_SCHEMA, showTables, "Schema '%s' does not exist", schema.getSchemaName()); } Expression predicate = equal(identifier("table_schema"), new StringLiteral(schema.getSchemaName())); Optional<String> likePattern = showTables.getLikePattern(); if (likePattern.isPresent()) { Expression likePredicate; Optional<String> escape = showTables.getEscape(); if (escape.isPresent()) { likePredicate = new LikePredicate(identifier("table_name"), new StringLiteral(likePattern.get()), new StringLiteral(escape.get())); } else { <START> likePredicate = new LikePredicate(identifier("table_name"), new StringLiteral(likePattern.get()), null); <END> } predicate = logicalAnd(predicate, likePredicate); } return simpleQuery( selectList(aliasedName("table_name", "Table")), from(schema.getCatalogName(), TABLE_TABLES), predicate, ordering(ascending("table_name"))); }</code><technical_language>Please add a constructor LikePredicate(Expression value, Expression pattern, Optional<Expression> escape), avoid @Nullable parameter in constructor</technical_language>

Target:
protected Node visitShowTables(ShowTables showTables, Void context) { CatalogSchemaName schema = createCatalogSchemaName(session, showTables, showTables.getSchema()); accessControl.checkCanShowTablesMetadata(session.getRequiredTransactionId(), session.getIdentity(), schema); if (!metadata.catalogExists(session, schema.getCatalogName())) { throw new SemanticException(MISSING_CATALOG, showTables, "Catalog '%s' does not exist", schema.getCatalogName()); } if (!metadata.schemaExists(session, schema)) { throw new SemanticException(MISSING_SCHEMA, showTables, "Schema '%s' does not exist", schema.getSchemaName()); } Expression predicate = equal(identifier("table_schema"), new StringLiteral(schema.getSchemaName())); Optional<String> likePattern = showTables.getLikePattern(); if (likePattern.isPresent()) { Expression likePredicate = new LikePredicate(identifier("table_name"), new StringLiteral(likePattern.get()), null); predicate = logicalAnd(predicate, likePredicate); } return simpleQuery( selectList(aliasedName("table_name", "Table")), from(schema.getCatalogName(), TABLE_TABLES), predicate, ordering(ascending("table_name"))); }
Source:
<code>private void disablePluginFormItems(NodeSourceConfiguration nodeSourceConfiguration) { PluginDescriptor focusedInfrastructurePlugin = nodeSourceConfiguration.getInfrastructurePluginDescriptor(); PluginDescriptor focusedPolicyPlugin = nodeSourceConfiguration.getPolicyPluginDescriptor(); List<String> dynamicParametersName = Stream.concat(getDynamicParametersName(focusedInfrastructurePlugin), getDynamicParametersName(focusedPolicyPlugin)) .collect(Collectors.toList()); <START> for (FormItem formItem : this.nodeSourcePluginsForm.getFields()) { <END> if (isNotDynamic(formItem, dynamicParametersName) && isFocusedPluginItem(focusedInfrastructurePlugin, focusedPolicyPlugin, formItem)) { formItem.disable(); } } }</code><technical_language>java this.nodeSourcePluginsForm.getFields() .steam() .filter(formItem -> isNotDynamic(formItem, dynamicParametersName) && isFocusedPluginItem(focusedInfrastructurePlugin, focusedPolicyPlugin, formItem)) .foreach(FormItem::disable);</technical_language>

Target:
private void disablePluginFormItems(NodeSourceConfiguration nodeSourceConfiguration) { PluginDescriptor focusedInfrastructurePlugin = nodeSourceConfiguration.getInfrastructurePluginDescriptor(); PluginDescriptor focusedPolicyPlugin = nodeSourceConfiguration.getPolicyPluginDescriptor(); List<String> dynamicParametersName = Stream.concat(getDynamicParametersName(focusedInfrastructurePlugin), getDynamicParametersName(focusedPolicyPlugin)) .collect(Collectors.toList()); Arrays.stream(this.nodeSourcePluginsForm.getFields()) .filter(formItem -> isNotDynamic(formItem.getName(), dynamicParametersName) && isFocusedPluginItem(focusedInfrastructurePlugin, focusedPolicyPlugin, formItem)) .forEach(FormItem::disable); }
Source:
<code>protected void confirmAndWaitForRefresh() { <START> waitExplicitly(1000); <END> confirmDialog(); waitUntil(stalenessOf(getDriver().findElement(By.tagName("html")))); }</code><technical_language>confirmDialog wait for presence visibility of "#ok" instead of explicit wait</technical_language>

Target:
protected void confirmAndWaitForRefresh() { waitUntil(visibilityOf(getDriver().findElement(By.id("ok")))); confirmDialog(); waitUntil(stalenessOf(getDriver().findElement(By.tagName("html")))); }
Source:
<code>public void testTwoCompensationHandlers() throws Exception { ParticipantCompletionCoordinatorRules.setParticipantCount(6); MyCompensationHandler.expectedData = "blah"; MyConfirmationHandler.expectedData = "blah"; getBAControler().beginBusinessActivity(); service.doWork("blah"); service.doWork("blah"); getBAControler().cancelBusinessActivity(); <START> Assert.assertEquals(true, MyCompensationHandler.dataAvailable); <END> Assert.assertEquals(false, MyConfirmationHandler.dataAvailable); }</code><technical_language>AssertTrue</technical_language>

Target:
public void testTwoCompensationHandlers() throws Exception { ParticipantCompletionCoordinatorRules.setParticipantCount(6); MyCompensationHandler.expectedData = "blah"; MyConfirmationHandler.expectedData = "blah"; getBAControler().beginBusinessActivity(); service.doWork("blah"); service.doWork("blah"); getBAControler().cancelBusinessActivity(); Assert.assertTrue(MyCompensationHandler.dataAvailable); Assert.assertFalse(MyConfirmationHandler.dataAvailable); }
Source:
<code>public boolean playersDead() { if(!this.isRunning()) { return false; } boolean b = true; for(Player p : this.players) { if (p.playerAlive()) { <START> b = false; <END> } } return b; }</code><technical_language>easier "return false;" bottom "return true" this save declare a variable for it. <layout,logic,performance</technical_language>

Target:
public boolean playersDead() { if (!this.isRunning()) { return false; } for (Player p : this.players) { if (p.hasLives()) { return false; } } return true; }
Source:
<code>public void write(final Interval interval) throws IOException { out.write(interval.getContig()); out.write(TAB); out.write(Integer.toString(interval.getStart())); out.write(TAB); out.write(Integer.toString(interval.getEnd())); out.write(TAB); <START> out.write(interval.isPositiveStrand() ? '+' : '-'); <END> out.write(TAB); out.write(interval.getName() != null ? interval.getName() : "."); out.newLine(); }</code><technical_language>Strand.POSITIVE Strand.NEGATIVE while here</technical_language>

Target:
public void write(final Interval interval) throws IOException { out.write(interval.getContig()); out.write(TAB); out.write(Integer.toString(interval.getStart())); out.write(TAB); out.write(Integer.toString(interval.getEnd())); out.write(TAB); out.write(interval.getStrand().encode()); out.write(TAB); out.write(interval.getName() != null ? interval.getName() : "."); out.newLine(); }
Source:
<code>protected void init() { super.init(); getApplicationSettings().setUploadProgressUpdatesEnabled(true); getResourceSettings().setThrowExceptionOnMissingResource(false); getRequestCycleSettings().addResponseFilter(new AjaxServerAndClientTimeFilter()); getDebugSettings().setAjaxDebugModeEnabled(true); <START> setHeaderResponseDecorator(response -> { <END> return new ResourceAggregator(new JavaScriptDeferHeaderResponse(response)); }); getComponentInitializationListeners().add(new IComponentInitializationListener() { @Override public void onInitialize(Component component) { if (component instanceof WebPage) { component.add(new AjaxNewWindowNotifyingBehavior()); } } }); mountPage("autocomplete", AutoCompletePage.class); mountPage("choice", ChoicePage.class); mountPage("clock", ClockPage.class); mountPage("editable-label", EditableLabelPage.class); mountPage("effects", EffectsPage.class); mountPage("form", FormPage.class); mountPage("guest-book", GuestBook.class); mountPage("lazy-loading", LazyLoadingPage.class); mountPage("links", LinksPage.class); mountPage("modal-window", ModalWindowPage.class); mountPage("on-change-ajax-behavior", OnChangeAjaxBehaviorPage.class); mountPage("pageables", PageablesPage.class); mountPage("ratings", RatingsPage.class); mountPage("tabbed-panel", TabbedPanelPage.class); mountPage("todo-list", TodoList.class); mountPage("world-clock", WorldClockPage.class); mountPage("upload", FileUploadPage.class); mountPage("download", AjaxDownloadPage.class); }</code><technical_language>this simplified tester.getApplication().setHeaderResponseDecorator(response -> new ResourceAggregator(new JavaScriptDeferHeaderResponse(response)));</technical_language>

Target:
protected void init() { super.init(); getApplicationSettings().setUploadProgressUpdatesEnabled(true); getResourceSettings().setThrowExceptionOnMissingResource(false); getRequestCycleSettings().addResponseFilter(new AjaxServerAndClientTimeFilter()); getDebugSettings().setAjaxDebugModeEnabled(true); setHeaderResponseDecorator(response -> new ResourceAggregator(new JavaScriptDeferHeaderResponse(response))); getComponentInitializationListeners().add(new IComponentInitializationListener() { @Override public void onInitialize(Component component) { if (component instanceof WebPage) { component.add(new AjaxNewWindowNotifyingBehavior()); } } }); mountPage("autocomplete", AutoCompletePage.class); mountPage("choice", ChoicePage.class); mountPage("clock", ClockPage.class); mountPage("editable-label", EditableLabelPage.class); mountPage("effects", EffectsPage.class); mountPage("form", FormPage.class); mountPage("guest-book", GuestBook.class); mountPage("lazy-loading", LazyLoadingPage.class); mountPage("links", LinksPage.class); mountPage("modal-window", ModalWindowPage.class); mountPage("on-change-ajax-behavior", OnChangeAjaxBehaviorPage.class); mountPage("pageables", PageablesPage.class); mountPage("ratings", RatingsPage.class); mountPage("tabbed-panel", TabbedPanelPage.class); mountPage("todo-list", TodoList.class); mountPage("world-clock", WorldClockPage.class); mountPage("upload", FileUploadPage.class); mountPage("download", AjaxDownloadPage.class); }
Source:
<code>public void testTask() throws Exception { ScriptingManager scriptingManager = cacheManager.getGlobalComponentRegistry().getComponent(ScriptingManager.class); <START> ScriptingTest.loadScript(scriptingManager, TEST_SCRIPT); <END> String result = (String) taskManager.runTask(TEST_SCRIPT, new TaskContext().addParameter("a", "a")).get(); assertEquals("a", result); }</code><technical_language>move this method a separate ScriptingTests class</technical_language>

Target:
public void testTask() throws Exception { ScriptingManager scriptingManager = cacheManager.getGlobalComponentRegistry().getComponent(ScriptingManager.class); loadScript(scriptingManager, TEST_SCRIPT); String result = (String) taskManager.runTask(TEST_SCRIPT, new TaskContext().addParameter("a", "a")).get(); assertEquals("a", result); }
Source:
<code>protected boolean isValidConnection(StorageServerConnections conn) { StorageType storageType = conn.getStorageType(); if (storageType == StorageType.NFS && !new NfsMountPointConstraint().isValid(conn.getConnection(), null)) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID); } if (storageType == StorageType.POSIXFS && StringUtils.isEmpty(conn.getVfsType())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if ((storageType == StorageType.POSIXFS || storageType == StorageType.NFS) && !validate(validateMountOptions())) { return false; } if (storageType == StorageType.ISCSI) { if (StringUtils.isEmpty(conn.getIqn())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (!isValidStorageConnectionPort(conn.getPort())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_PORT); } } if (storageType == StorageType.GLUSTERFS) { StorageConnectionValidator validator = new StorageConnectionValidator(conn); <START> if (!validate(validateVolumeIdAndupdatePath(conn)) && !validate(validator.canVDSConnectToGlusterfs(getVds()))) { <END> return false; } } if (checkIsConnectionFieldEmpty(conn)) { return false; } return true; }</code><technical_language>Please formatter. line is long broken</technical_language>

Target:
protected boolean isValidConnection(StorageServerConnections conn) { StorageType storageType = conn.getStorageType(); if (storageType == StorageType.NFS && !new NfsMountPointConstraint().isValid(conn.getConnection(), null)) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID); } if (storageType == StorageType.POSIXFS && StringUtils.isEmpty(conn.getVfsType())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if ((storageType == StorageType.POSIXFS || storageType == StorageType.NFS) && !validate(validateMountOptions())) { return false; } if (storageType == StorageType.ISCSI) { if (StringUtils.isEmpty(conn.getIqn())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (!isValidStorageConnectionPort(conn.getPort())) { return failValidation(EngineMessage.VALIDATION_STORAGE_CONNECTION_INVALID_PORT); } } if (storageType == StorageType.GLUSTERFS) { StorageConnectionValidator validator = new StorageConnectionValidator(conn); if (!validate(validateVolumeIdAndUpdatePath(conn)) && !validate(validator.canVDSConnectToGlusterfs(getVds()))) { return false; } } if (checkIsConnectionFieldEmpty(conn)) { return false; } return true; }
Source:
<code>private static String getTemporaryDir(ITmfTrace trace) { String name = trace.getName(); String path = trace.getPath(); if (path == null) { String prefix = FilenameUtils.getPrefix(trace.getPath()); if (prefix != null) { name = <START> trace.getPath().substring(prefix.length()); <END> } } String pathName = getTemporaryDirPath() + File.separator + name + File.separator; File dir = new File(pathName); if (!dir.exists()) { dir.mkdirs(); } return pathName; }</code><technical_language>establish this null</technical_language>

Target:
private static String getTemporaryDir(ITmfTrace trace) { String name = trace.getName(); String path = trace.getPath(); if (path != null) { String prefix = FilenameUtils.getPrefix(trace.getPath()); if (prefix != null) { name = trace.getPath().substring(prefix.length()); } } String pathName = getTemporaryDirPath() + File.separator + name + File.separator; File dir = new File(pathName); if (!dir.exists()) { dir.mkdirs(); } return pathName; }
Source:
<code>public void waitForReplication() { try { allPushTasksFinished.await(); } catch (InterruptedException e) { <START> log.error("It is interrupted while waiting replication to be completed");; <END> } }</code><technical_language>show this problem user, give calling code (i.e.: StartCommand) a chance detect interrupted. rethrowing, returning a boolean success, copying error pushProcessing option? ------------- Nit: Double semi-colon end</technical_language>

Target:
public void waitForReplication() throws InterruptedException { allPushTasksFinished.await(); }
Source:
<code>private static ManifestElement[] getGenericCapabilities(Dictionary<String, String> manifest, String[][] genericAliases) throws BundleException { ManifestElement[] genericCapabilities = ManifestElement.parseHeader(GENERIC_CAPABILITY, manifest.get(GENERIC_CAPABILITY)); List<ManifestElement> aliasList = null; if (genericAliases.length > 0) { aliasList = new ArrayList<>(genericCapabilities == null ? 0 : genericCapabilities.length); for (String[] <START> genericAliase : <END> genericAliases) { ManifestElement[] aliasCapabilities = ManifestElement.parseHeader(genericAliase[0], manifest.get(genericAliase[0])); if (aliasCapabilities == null) continue; for (ManifestElement aliasCapabilitie : aliasCapabilities) { StringBuffer strBuf = new StringBuffer(); strBuf.append(aliasCapabilitie.getValue()).append(':').append(genericAliase[2]); for (Enumeration<String> keys = aliasCapabilitie.getKeys(); keys != null && keys.hasMoreElements();) { String key = keys.nextElement(); strBuf.append("; ").append(key).append("=\"").append(aliasCapabilitie.getAttribute(key)).append("\""); } ManifestElement[] withTypes = ManifestElement.parseHeader(genericAliase[0], strBuf.toString()); aliasList.add(withTypes[0]); } } } if (aliasList == null || aliasList.size() == 0) return genericCapabilities; if (genericCapabilities != null) for (ManifestElement genericCapabilitie : genericCapabilities) { aliasList.add(genericCapabilitie); } return aliasList.toArray(new ManifestElement[aliasList.size()]); }</code><technical_language>name genericAlias</technical_language>

Target:
private static ManifestElement[] getGenericCapabilities(Dictionary<String, String> manifest, String[][] genericAliases) throws BundleException { ManifestElement[] genericCapabilities = ManifestElement.parseHeader(GENERIC_CAPABILITY, manifest.get(GENERIC_CAPABILITY)); List<ManifestElement> aliasList = null; if (genericAliases.length > 0) { aliasList = new ArrayList<>(genericCapabilities == null ? 0 : genericCapabilities.length); for (String[] genericAlias : genericAliases) { ManifestElement[] aliasCapabilities = ManifestElement.parseHeader(genericAlias[0], manifest.get(genericAlias[0])); if (aliasCapabilities == null) continue; for (ManifestElement aliasCapability : aliasCapabilities) { StringBuffer strBuf = new StringBuffer(); strBuf.append(aliasCapability.getValue()).append(':').append(genericAlias[2]); for (Enumeration<String> keys = aliasCapability.getKeys(); keys != null && keys.hasMoreElements();) { String key = keys.nextElement(); strBuf.append("; ").append(key).append("=\"").append(aliasCapability.getAttribute(key)).append("\""); } ManifestElement[] withTypes = ManifestElement.parseHeader(genericAlias[0], strBuf.toString()); aliasList.add(withTypes[0]); } } } if (aliasList == null || aliasList.size() == 0) return genericCapabilities; if (genericCapabilities != null) for (ManifestElement genericCapability : genericCapabilities) { aliasList.add(genericCapability); } return aliasList.toArray(new ManifestElement[aliasList.size()]); }
Source:
<code>private static FacesMessage msgForSelectEdit(String ofType) { <START> return HelperUtil.getMsgWarn(MessageFormat.format("Select a {0} for edit.", ofType.toLowerCase())); <END> }</code><technical_language>I decide put "a" "an" in constant removed for message-text</technical_language>

Target:
private static FacesMessage msgForSelectEdit(String ofType) { return HelperUtil.getMsgWarn(MessageFormat.format("Select {0} for edit.", ofType.toLowerCase())); }
Source:
<code>GoCommand(ArtifactoryBuildInfoClientBuilder clientBuilder, Path path, Log logger) throws IOException { <START> this.clientBuilder = clientBuilder; <END> this.logger = logger; this.path = path; }</code><technical_language>^ This method longer throws IOException</technical_language>

Target:
GoCommand(ArtifactoryBuildInfoClientBuilder clientBuilder, Path path, Log logger) { this.clientBuilder = clientBuilder; this.logger = logger; this.path = path; }
Source:
<code>private DMSVariableType addDataTypeVariableTypeIfNecessary(final VariableTypeList variableTypeList, final String programUUID) throws MiddlewareException { DMSVariableType variableType = variableTypeList.findById(TermId.DATASET_TYPE); if (variableType == null) { variableType = new DMSVariableType("DATASET_TYPE", "Dataset type", this.getStandardVariable(TermId.DATASET_TYPE, programUUID), 3); variableType.setRole(PhenotypicType.DATASET); variableTypeList.makeRoom(3); variableTypeList.add(variableType); } return variableType; <START> } <END></code><technical_language>Code cleanup: Remove throws MiddlewareException throws MiddlewareQueryException for this class</technical_language>

Target:
private DMSVariableType addDataTypeVariableTypeIfNecessary(final VariableTypeList variableTypeList, final String programUUID) throws MiddlewareQueryException { DMSVariableType variableType = variableTypeList.findById(TermId.DATASET_TYPE); if (variableType == null) { variableType = new DMSVariableType("DATASET_TYPE", "Dataset type", this.getStandardVariable(TermId.DATASET_TYPE, programUUID), 3); variableType.setRole(PhenotypicType.DATASET); variableTypeList.makeRoom(3); variableTypeList.add(variableType); } return variableType; }
Source:
<code>private void initVmInitEnabled(VmInit vmInit, boolean isInitialized) { if (vmInit == null) { getIsCloudInitEnabled().setEntity(false); getIsSysprepEnabled().setEntity(false); getAttachFloppy().setEntity(false); } else if (!isInitialized) { <START> if (!vm.getCompatibilityVersion().greaterOrEquals(Version.v4_4) && getIsWindowsOS()) { <END> getIsSysprepEnabled().setEntity(true); getAttachFloppy().setEntity(true); } else { getIsCloudInitEnabled().setEntity(true); } } }</code><technical_language>floppy support it. goal of change is mechanism, ditch feature entirely. way, this osinfo, hardcoded levels</technical_language>

Target:
private void initVmInitEnabled(VmInit vmInit, boolean isInitialized) { if (vmInit == null) { getIsCloudInitEnabled().setEntity(false); getIsSysprepEnabled().setEntity(false); getAttachFloppy().setEntity(false); } else if (!isInitialized) { if (getIsWindowsOS()) { getIsSysprepEnabled().setEntity(true); getAttachFloppy().setEntity(true); } else { getIsCloudInitEnabled().setEntity(true); } } }
Source:
<code>private void createHybridRole(String roleName, String[] userList, org.wso2.carbon.user.api.Permission[] permissions) throws UserStoreException { try { hybridRoleManager.addHybridRole(roleName, userList); } catch (UserStoreException e) { <START> if (hybridRoleManager.isExistingRole(roleName)) { <END> handleRoleAlreadyExistException(roleName, userList, permissions); } throw e; } }</code><technical_language>check error code do this lookup? otherwise, end this lookup for exception scenarios, it</technical_language>

Target:
private void createHybridRole(String roleName, String[] userList, org.wso2.carbon.user.api.Permission[] permissions) throws UserStoreException { try { hybridRoleManager.addHybridRole(roleName, userList); } catch (UserStoreException e) { if (ERROR_CODE_ROLE_ALREADY_EXISTS.getCode().equals(e.getErrorCode())) { handleRoleAlreadyExistException(roleName, userList, permissions); } throw e; } }
Source:
<code>public View getView(int position, View convertView, ViewGroup parent) { View element = convertView; if(element == null){ LayoutInflater inflater = (LayoutInflater) this.mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); element = inflater.inflate(R.layout.song_item, null); } View userColor = (View) element.findViewById(R.id.userColor); TextView title = (TextView)element.findViewById(R.id.title); TextView artist = (TextView) element.findViewById(R.id.artist); TextView album = (TextView) element.findViewById(R.id.album); ImageButton addButton = (ImageButton) element.findViewById(R.id.add_to_playlist); <START> addButton.setOnClickListener(this); <END> addButton.setTag(position); userColor.setBackgroundColor(Color.parseColor(users.get(metadataList.get(position).getUsername()))); title.setText(metadataList.get(position).getTitle()); artist.setText(metadataList.get(position).getArtist()); album.setText(metadataList.get(position).getAlbum()); return element; }</code><technical_language>a separate method instead of adapter onclick listener</technical_language>

Target:
public View getView(int position, View convertView, ViewGroup parent) { View element = convertView; if(element == null){ LayoutInflater inflater = (LayoutInflater) this.mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); element = inflater.inflate(R.layout.song_item, null); } View userColor = (View) element.findViewById(R.id.user_color); TextView title = (TextView)element.findViewById(R.id.title); TextView artist = (TextView) element.findViewById(R.id.artist); TextView album = (TextView) element.findViewById(R.id.album); ImageButton addButton = (ImageButton) element.findViewById(R.id.add_to_playlist); addButton.setTag(position); userColor.setBackgroundColor(Color.parseColor(users.get(metadataList.get(position).getUsername()))); title.setText(metadataList.get(position).getTitle()); artist.setText(metadataList.get(position).getArtist()); album.setText(metadataList.get(position).getAlbum()); artist.setMaxWidth(parent.getWidth()/2); return element; }
Source:
<code>public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception { URI uri = new URI(useSsl ? "https" : "http", null, hostname, port, uriPath, null, null); HttpURLConnection connection = (HttpURLConnection)uri.toURL().openConnection(); if (useSsl && !validateSsl) { X509TrustManager trustAllCert = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[]{trustAllCert}, new java.security.SecureRandom()); ((HttpsURLConnection)connection).setSSLSocketFactory(sc.getSocketFactory()); ((HttpsURLConnection)connection).setHostnameVerifier(new HostnameVerifier(){ public boolean verify(String host, SSLSession session){ return true; } }); } connection.addRequestProperty("Accept", mimeType); connection.addRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(userInfo.getBytes())); <START> StringBuilder str = new StringBuilder(); <END> InputStream in = new BufferedInputStream(connection.getInputStream()); try { for(;;) { int b = in.read(); if ( b < 0 ) { break; } str.append((char)(b & 0xff)); } } finally { CloseableUtils.closeQuietly(in); } return str.toString(); }</code><technical_language>Guava's CharStreams here. cleaner: java Reader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream())); try { return CharStreams.toString(in); } finally { CloseableUtils.closeQuietly(in); }</technical_language>

Target:
public String getRaw(String hostname, int port, String uriPath, String mimeType) throws Exception { URI uri = new URI(useSsl ? "https" : "http", null, hostname, port, uriPath, null, null); HttpURLConnection connection = (HttpURLConnection)uri.toURL().openConnection(); if (useSsl && !validateSsl) { X509TrustManager trustAllCert = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException public X509Certificate[] getAcceptedIssuers() { return null; } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[]{trustAllCert}, new java.security.SecureRandom()); ((HttpsURLConnection)connection).setSSLSocketFactory(sc.getSocketFactory()); ((HttpsURLConnection)connection).setHostnameVerifier(new HostnameVerifier(){ public boolean verify(String host, SSLSession session){ return true; } }); } connection.addRequestProperty("Accept", mimeType); connection.addRequestProperty("Authorization", "Basic " + new BASE64Encoder().encode(userInfo.getBytes())); Reader in = new InputStreamReader(new BufferedInputStream(connection.getInputStream())); try { return CharStreams.toString(in); } finally { CloseableUtils.closeQuietly(in); } }
Source:
<code>public int compare(TestdataObject a, TestdataObject b) { return new CompareToBuilder() .append(a.getCode(), b.getCode()) <START> .toComparison(); <END> }</code><technical_language>Please Comparator.comparing().thenComparing() instead avoid create class with</technical_language>

Target:
public int compare(TestdataObject a, TestdataObject b) { return COMPARATOR.compare(a, b); }
Source:
<code>default <T> CompletableFuture<Long> parseLimitedStreamRecurse(byte[] prefix, Function<Cborable, T> fromCbor, Consumer<T> accumulator, int objectsToSkip, int maxObjectsToRead, long maxBytesToRead) { if (maxObjectsToRead == 0) return CompletableFuture.completedFuture(0L); byte[] buf = new byte[Chunk.MAX_SIZE]; System.arraycopy(prefix, 0, buf, 0, prefix.length); ByteArrayInputStream in = new ByteArrayInputStream(buf); return readIntoArray(buf, prefix.length, (int) Math.min((long)(buf.length - prefix.length), maxBytesToRead)) .thenCompose(bytesRead -> { int toSkip = objectsToSkip; int objectsToRead = maxObjectsToRead; for (int localOffset = 0; localOffset < bytesRead;) { try { CborObject readObject = CborObject.read(in, bytesRead); if (toSkip > 0) toSkip--; else { objectsToRead--; accumulator.accept(fromCbor.apply(readObject)); } localOffset += readObject.toByteArray().length; <START> } catch (RuntimeException e) { <END> int fromThisChunk = localOffset; return parseLimitedStreamRecurse(Arrays.copyOfRange(buf, localOffset, bytesRead), fromCbor, accumulator, toSkip, objectsToRead, maxBytesToRead - bytesRead) .thenApply(rest -> rest + fromThisChunk); } } return parseLimitedStream(fromCbor, accumulator, toSkip, objectsToRead, maxBytesToRead - bytesRead) .thenApply(rest -> rest + bytesRead); }); }</code><technical_language>need a description explain exception consequence</technical_language>

Target:
default <T> CompletableFuture<Long> parseLimitedStreamRecurse(byte[] prefix, Function<Cborable, T> fromCbor, Consumer<T> accumulator, int objectsToSkip, int maxObjectsToRead, long maxBytesToRead) { if (maxObjectsToRead == 0) return CompletableFuture.completedFuture(0L); byte[] buf = new byte[Chunk.MAX_SIZE]; System.arraycopy(prefix, 0, buf, 0, prefix.length); ByteArrayInputStream in = new ByteArrayInputStream(buf); return readIntoArray(buf, prefix.length, (int) Math.min((long)(buf.length - prefix.length), maxBytesToRead)) .thenCompose(bytesRead -> { int toSkip = objectsToSkip; int objectsToRead = maxObjectsToRead; for (int localOffset = 0; localOffset < bytesRead;) { try { CborObject readObject = CborObject.read(in, bytesRead); if (toSkip > 0) toSkip--; else { objectsToRead--; accumulator.accept(fromCbor.apply(readObject)); } localOffset += readObject.toByteArray().length; if (objectsToRead == 0) return Futures.of((long)localOffset); } catch (RuntimeException e) { int fromThisChunk = localOffset; return parseLimitedStreamRecurse(Arrays.copyOfRange(buf, localOffset, bytesRead), fromCbor, accumulator, toSkip, objectsToRead, maxBytesToRead - bytesRead) .thenApply(rest -> rest + fromThisChunk); } } return parseLimitedStream(fromCbor, accumulator, toSkip, objectsToRead, maxBytesToRead - bytesRead) .thenApply(rest -> rest + bytesRead); }); }
Source:
<code>public static void sendSmsCbReceivedBroadcast(@NonNull Context context, @Nullable UserHandle user, @NonNull SmsCbMessage smsCbMessage, @Nullable BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, int slotIndex) { <START> int status = context.checkCallingOrSelfPermission( "android.permission.GRANT_RUNTIME_PERMISSIONS_TO_TELEPHONY_DEFAULTS"); <END> if (status == PackageManager.PERMISSION_DENIED) { throw new SecurityException( "Caller does not have permission to send SMS_CB_RECEIVED_ACTION broadcast " + "for background receivers"); } Intent backgroundIntent = new Intent(Telephony.Sms.Intents.SMS_CB_RECEIVED_ACTION); backgroundIntent.putExtra(EXTRA_MESSAGE, smsCbMessage); backgroundIntent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); putPhoneIdAndSubIdExtra(context, backgroundIntent, slotIndex); String receiverPermission = Manifest.permission.RECEIVE_SMS; String receiverAppOp = AppOpsManager.OPSTR_RECEIVE_SMS; if (user != null) { context.createContextAsUser(user, 0).sendOrderedBroadcast(backgroundIntent, receiverPermission, receiverAppOp, resultReceiver, scheduler, initialCode, null, null); } else { context.sendOrderedBroadcast(backgroundIntent, receiverPermission, receiverAppOp, resultReceiver, scheduler, initialCode, null, null); } }</code><technical_language>of original issue raised this permission check; run in caller's app space (and IPC) guaranteeing permission check occurs validly. need do actual sending of intent Telephony do permission check there</technical_language>

Target:
public static void sendSmsCbReceivedBroadcast(@NonNull Context context, @Nullable UserHandle user, @NonNull SmsCbMessage smsCbMessage, @Nullable BroadcastReceiver resultReceiver, @Nullable Handler scheduler, int initialCode, int slotIndex) { Intent backgroundIntent = new Intent(Telephony.Sms.Intents.SMS_CB_RECEIVED_ACTION); backgroundIntent.putExtra(EXTRA_MESSAGE, smsCbMessage); backgroundIntent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); putPhoneIdAndSubIdExtra(context, backgroundIntent, slotIndex); String receiverPermission = Manifest.permission.RECEIVE_SMS; String receiverAppOp = AppOpsManager.OPSTR_RECEIVE_SMS; if (user != null) { context.createContextAsUser(user, 0).sendOrderedBroadcast(backgroundIntent, receiverPermission, receiverAppOp, resultReceiver, scheduler, initialCode, null, null); } else { context.sendOrderedBroadcast(backgroundIntent, receiverPermission, receiverAppOp, resultReceiver, scheduler, initialCode, null, null); } }
Source:
<code>protected void hotCodeError(int code, IJavaDebugTarget target, Exception exception) { int behavior = server.getAttribute(PROPERTY_HOTCODE_BEHAVIOR, PROMPT); if( behavior == PROMPT ) { <START> Object result = getPrompter().promptUser(code, server, exception); <END> if( result instanceof Integer) { behavior = ((Integer)result).intValue(); } } if( behavior == RESTART_MODULE) { restartModules(); } else if( behavior == RESTART_SERVER) { restartServer(); } }</code><technical_language>prompter supposed handle _Every_ kind of codes ? specific usecased prompts</technical_language>

Target:
protected void hotCodeError(int code, IJavaDebugTarget target, Exception exception) { int behavior = server.getAttribute(PROPERTY_HOTCODE_BEHAVIOR, PROMPT); if( behavior == PROMPT ) { Object result = getPrompter().promptUser(code, server, exception); if( result instanceof Integer) { behavior = ((Integer)result).intValue(); } } if( behavior == RESTART_MODULE) { restartModules(); } else if( behavior == RESTART_SERVER) { restartServer(); } else if( behavior == TERMINATE ) { server.stop(true); } }
Source:
<code><START> private boolean <END> checkAndDisableCLIScheduler() { GlusterVolumeEntity metaVolume = getGlusterVolumeDao().getByName(getVdsGroupId(), GlusterConstants.GLUSTER_META_VOLUME_NAME); if (metaVolume != null) { VDSGroup cluster = getVdsGroup(); if (cluster.getGlusterCliBasedScheduling()) { VDSReturnValue retValue = runVdsCommand(VDSCommandType.OverrideGlusterVolumeSnapshotSchedule, new GlusterVolumeSnapshotSchedulingVDSParameters(getUpServer().getId(), true)); setSucceeded(retValue.getSucceeded()); if (!retValue.getSucceeded()) { handleVdsError(AuditLogType.GLUSTER_CLI_SNAPSHOT_SCHEDULE_DISABLE_FAILED, retValue.getVdsError() .getMessage()); return false; } else { cluster.setGlusterCliBasedScheduling(false); getVdsGroupDAO().update(cluster); } } } return true; }</code><technical_language>move this internal command, is called 2 places</technical_language>

Target:
private boolean checkAndDisableCLIScheduler() { GlusterVolumeEntity metaVolume = getGlusterVolumeDao().getByName(getVdsGroupId(), Config.<String> getValue(ConfigValues.GlusterMetaVolumeName)); VDSGroup cluster = getVdsGroup(); if (metaVolume != null && cluster.getIsGlusterCliBasedSchedulingOn()) { VdcReturnValueBase returnValue = runInternalAction(VdcActionType.DisableGlusterCliSnapshotScheduleInternal, new DisableGlusterCliSnapshotScheduleParameters(getGlusterVolumeId(), true)); return returnValue.getSucceeded(); } return true; }
Source:
<code>public IResource findMember(IReferencePoint referencePoint, IPath referencePointRelativePath) { if (referencePoint == null) throw new IllegalArgumentException("Reference point is null"); if (referencePointRelativePath == null) throw new IllegalArgumentException("Path is null"); org.eclipse.core.resources.IProject project = getProject(referencePoint); if (project == null) <START> throw new NullPointerException( <END> "For reference point " + referencePoint + " does'nt exist a project."); return project.findMember(referencePointRelativePath); }</code><technical_language>a suggestion remove followup NPE check Objects.requireNonNull suggestion org.eclipse.core.resources.IProject project = Objects.requireNonNull(getProject(referencePoint), "No project for reference point: " + referencePoint);</technical_language>

Target:
public IResource findMember(IReferencePoint referencePoint, IPath referencePointRelativePath) { checkArgument(referencePoint, "Reference point is null"); checkArgument(referencePointRelativePath, "ReferencePointsRelativePath is null"); IProject project = Objects.requireNonNull(getProject(referencePoint)); return project.findMember(referencePointRelativePath); }
Source:
<code>private VolumeType getVolumeTypeForDomain() { <START> if (null == volumeTypeForDomain) { <END> StorageDomainStatic sdStatic = DbFacade.getInstance().getStorageDomainStaticDao().get(storageDomainId); volumeTypeForDomain = HibernateVmCommand.getMemoryVolumeTypeForStorageDomain(sdStatic.getStorageType()); } return volumeTypeForDomain; }</code><technical_language>is null left side</technical_language>

Target:
private VolumeType getVolumeTypeForDomain() { if (volumeTypeForDomain == null) { StorageDomainStatic sdStatic = DbFacade.getInstance().getStorageDomainStaticDao().get(storageDomainId); volumeTypeForDomain = HibernateVmCommand.getMemoryVolumeTypeForStorageDomain(sdStatic.getStorageType()); } return volumeTypeForDomain; }
Source:
<code>private void startPoller() { poller = new Timer() { private int delay = REFRESH_POLL_PERIOD; @Override public void run() { if (!isAttached()) { return; } else if (!UserActivityMonitor.isActive()) { cancel(); <START> delay = REFRESH_IDLE_PERIOD; <END> scheduleRepeating(delay); } loadChangeInfo(false, new AsyncCallback<ChangeInfo>() { @Override public void onSuccess(ChangeInfo info) { if (isAttached() && !info.updated().equals(lastDisplayedUpdate)) { showUpdates(info); } } @Override public void onFailure(Throwable caught) { if (isAttached()) { cancel(); delay = (int) Math.max( delay * (1.5 + Math.random()), REFRESH_MAX_PERIOD); scheduleRepeating(delay); } } }); } }; poller.scheduleRepeating(REFRESH_POLL_PERIOD); }</code><technical_language>polling same? update status user returns. add a callback UserActivityMonitor for activity changes</technical_language>

Target:
private void startPoller() { updateCheck = new UpdateCheckTimer(this); updateCheck.schedule(); handlers.add(UserActivityMonitor.addValueChangeHandler(updateCheck)); }
Source:
<code>public Map<String, Set<String>> calculateHostGroups(Map<String, Set<String>> hostComponentMap) { List<Set<String>> hostGroups = newArrayList( hostComponentMap.entrySet().stream().collect( groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toCollection(TreeSet::new))) ).values()); hostGroups.sort(comparing(hosts -> hosts.iterator().next())); Map<String, Set<String>> hostgroupMap = IntStream.range(0, hostGroups.size()) .mapToObj(i -> Pair.of("host_group_" + (i + 1), hostGroups.get(i))) <START> .collect(toMap(Pair::getKey, Pair::getValue)); <END> return hostgroupMap; }</code><technical_language>Is skip mapToObj step, key in toMap? Creating a Pair object unnecessary</technical_language>

Target:
public Map<String, Set<String>> calculateHostGroups(Map<String, Set<String>> hostComponentMap) { List<Set<String>> hostGroups = newArrayList( hostComponentMap.entrySet().stream().collect( groupingBy(Map.Entry::getValue, mapping(Map.Entry::getKey, toCollection(TreeSet::new))) ).values()); hostGroups.sort(comparing(hosts -> hosts.iterator().next())); Map<String, Set<String>> hostgroupMap = IntStream.range(0, hostGroups.size()).boxed() .collect(toMap(i -> "host_group_" + (i + 1), i -> hostGroups.get(i))); return hostgroupMap; }