java.util.LinkedHashSet Java Examples
The following examples show how to use
java.util.LinkedHashSet.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DecisionTreeRegressionModelInfoAdapter.java From spark-transformers with Apache License 2.0 | 6 votes |
public DecisionTreeModelInfo getModelInfo(final DecisionTreeRegressionModel decisionTreeModel, final DataFrame df) { final DecisionTreeModelInfo treeInfo = new DecisionTreeModelInfo(); Node rootNode = decisionTreeModel.rootNode(); treeInfo.setRoot( DecisionNodeAdapterUtils.adaptNode(rootNode)); final Set<String> inputKeys = new LinkedHashSet<String>(); inputKeys.add(decisionTreeModel.getFeaturesCol()); inputKeys.add(decisionTreeModel.getLabelCol()); treeInfo.setInputKeys(inputKeys); final Set<String> outputKeys = new LinkedHashSet<String>(); outputKeys.add(decisionTreeModel.getPredictionCol()); treeInfo.setOutputKeys(outputKeys); return treeInfo; }
Example #2
Source File: SqlValidatorUtil.java From Bats with Apache License 2.0 | 6 votes |
/** Computes the cube of bit sets. * * <p>For example, <code>rollup({0}, {1})</code> * returns <code>({0, 1}, {0}, {})</code>. * * <p>Bit sets are not necessarily singletons: * <code>rollup({0, 2}, {3, 5})</code> * returns <code>({0, 2, 3, 5}, {0, 2}, {})</code>. */ @VisibleForTesting public static ImmutableList<ImmutableBitSet> cube( List<ImmutableBitSet> bitSets) { // Given the bit sets [{1}, {2, 3}, {5}], // form the lists [[{1}, {}], [{2, 3}, {}], [{5}, {}]]. final Set<List<ImmutableBitSet>> builder = new LinkedHashSet<>(); for (ImmutableBitSet bitSet : bitSets) { builder.add(Arrays.asList(bitSet, ImmutableBitSet.of())); } Set<ImmutableBitSet> flattenedBitSets = new LinkedHashSet<>(); for (List<ImmutableBitSet> o : EnumeratorUtils.product(builder)) { flattenedBitSets.add(ImmutableBitSet.union(o)); } return ImmutableList.copyOf(flattenedBitSets); }
Example #3
Source File: JDesktopPane.java From TencentKona-8 with GNU General Public License v2.0 | 6 votes |
private static Collection<JInternalFrame> getAllFrames(Container parent) { int i, count; Collection<JInternalFrame> results = new LinkedHashSet<>(); count = parent.getComponentCount(); for (i = 0; i < count; i++) { Component next = parent.getComponent(i); if (next instanceof JInternalFrame) { results.add((JInternalFrame) next); } else if (next instanceof JInternalFrame.JDesktopIcon) { JInternalFrame tmp = ((JInternalFrame.JDesktopIcon) next).getInternalFrame(); if (tmp != null) { results.add(tmp); } } else if (next instanceof Container) { results.addAll(getAllFrames((Container) next)); } } return results; }
Example #4
Source File: SimpleClassWriter.java From coroutines with GNU Lesser General Public License v3.0 | 6 votes |
/** * Derives common super class from the super name mapping passed in to the constructor. * @param type1 the internal name of a class. * @param type2 the internal name of another class. * @return the internal name of the common super class of the two given classes * @throws NullPointerException if any argument is {@code null} */ @Override protected String getCommonSuperClass(final String type1, final String type2) { Validate.notNull(type1); Validate.notNull(type2); infoRepo.getInformation(type1); LinkedHashSet<String> type1Hierarchy = flattenHierarchy(type1); LinkedHashSet<String> type2Hierarchy = flattenHierarchy(type2); for (String testType1 : type1Hierarchy) { for (String testType2 : type2Hierarchy) { if (testType1.equals(testType2)) { return testType1; } } } return "java/lang/Object"; // is this correct behaviour? shouldn't both type1 and type2 ultimately contain Object? }
Example #5
Source File: ReadOnlyGeneticVariantTriTyper.java From systemsgenetics with GNU General Public License v3.0 | 6 votes |
@Override public List<Alleles> getSampleVariants() { List<Alleles> sampleVariantAlleles = Collections.unmodifiableList(sampleVariantsProvider.getSampleVariants(this)); if (this.alleles == null) { //set alleles here LinkedHashSet<Allele> variantAlleles = new LinkedHashSet<Allele>(2); for (Alleles alleles2 : sampleVariantAlleles) { for (Allele allele : alleles2) { if (allele != allele.ZERO) { variantAlleles.add(allele); } } } this.alleles = Alleles.createAlleles(new ArrayList<Allele>(variantAlleles)); } return sampleVariantAlleles; }
Example #6
Source File: SDGeneratorManager.java From spring-data-generator with MIT License | 6 votes |
private Set<String> validateExtends(Class<?>[] additionalExtends){ Class<?> extendTemporal; boolean errorValidate = Boolean.FALSE; Set<String> additionalExtendsList = new LinkedHashSet<>(); for (int i = 0; i < additionalExtends.length; i++) { extendTemporal = additionalExtends[i]; SDLogger.addAdditionalExtend(extendTemporal.getName()); if (!extendTemporal.isInterface()) { SDLogger.addError( String.format("'%s' is not a interface!", extendTemporal.getName())); errorValidate = Boolean.TRUE; } else { additionalExtendsList.add(extendTemporal.getName()); } } if (errorValidate) { return null; } return additionalExtendsList; }
Example #7
Source File: StartupContext.java From vertx-vaadin with MIT License | 6 votes |
@Override public Set<String> getResourcePaths(String path) { if (path.startsWith("/")) { path = path.substring(1); } String relativePath = path; Pattern pattern; if (path.isEmpty()) { pattern = Pattern.compile("^((?:META-INF/resources/|)[^/]+(?:/|$))"); } else { pattern = Pattern.compile(String.format("^((?:META-INF/resources/%1$s|%1$s)/[^/]+(?:/|$))", relativePath)); } return startupContext.resources.stream() .filter(p -> p.startsWith("META-INF/resources/" + relativePath) || p.startsWith(relativePath)) .map(p -> { Matcher matcher = pattern.matcher(p); matcher.find(); return matcher.group(1); }) .collect(Collectors.toCollection(LinkedHashSet::new)); }
Example #8
Source File: FirstSourceURLProvider.java From netbeans with Apache License 2.0 | 6 votes |
private Set<FileObject> computeModuleRoots() { Set<FileObject> projectDirectories = new LinkedHashSet<>(); String[] sourceRoots = sourcePath.getSourceRoots(); for (String src : sourceRoots) { FileObject fo = getFileObject(src); if (fo == null) { continue; } Project p = getProject(fo); if (p == null) { continue; } projectDirectories.add(p.getProjectDirectory()); } return projectDirectories; }
Example #9
Source File: ConsumesRequestCondition.java From spring-analysis-note with MIT License | 6 votes |
private static Set<ConsumeMediaTypeExpression> parseExpressions(String[] consumes, @Nullable String[] headers) { Set<ConsumeMediaTypeExpression> result = new LinkedHashSet<>(); if (headers != null) { for (String header : headers) { HeaderExpression expr = new HeaderExpression(header); if ("Content-Type".equalsIgnoreCase(expr.name) && expr.value != null) { for (MediaType mediaType : MediaType.parseMediaTypes(expr.value)) { result.add(new ConsumeMediaTypeExpression(mediaType, expr.isNegated)); } } } } for (String consume : consumes) { result.add(new ConsumeMediaTypeExpression(consume)); } return result; }
Example #10
Source File: EncodingConflictOutputHandler.java From workcraft with MIT License | 6 votes |
private LinkedHashSet<Core> convertSolutionsToCores(List<Solution> solutions) { LinkedHashSet<Core> cores = new LinkedHashSet<>(); for (Solution solution: solutions) { String comment = solution.getComment(); Matcher matcher = SIGNAL_PATTERN.matcher(comment); String signalName = matcher.find() ? matcher.group(1) : null; Core core = new Core(solution.getMainTrace(), solution.getBranchTrace(), signalName); boolean isDuplicateCore = cores.contains(core); if (!isDuplicateCore) { core.setColor(colorGenerator.updateColor()); cores.add(core); } if (MpsatVerificationSettings.getDebugCores()) { if (signalName == null) { LogUtils.logMessage("Encoding conflict:"); } else { LogUtils.logMessage("Encoding conflict for signal '" + signalName + "':"); } LogUtils.logMessage(" Configuration 1: " + solution.getMainTrace()); LogUtils.logMessage(" Configuration 2: " + solution.getBranchTrace()); LogUtils.logMessage(" Conflict core" + (isDuplicateCore ? " (duplicate)" : "") + ": " + core); LogUtils.logMessage(""); } } return cores; }
Example #11
Source File: ListenerProvider.java From binnavi with Apache License 2.0 | 6 votes |
/** * Adds a listener to the listener provider. * * @param listener The listener to add. * * @throws NullPointerException Thrown if the listener object is null. * @throws IllegalStateException Thrown if the listener is already managed by the listener * provider. */ public void addListener(final T listener) { Preconditions.checkNotNull(listener, "Internal Error: Listener cannot be null"); if (m_listeners == null) { synchronized (this) { if (m_listeners == null) { m_listeners = new LinkedHashSet<WeakReference<T>>(); } } } synchronized (m_listeners) { if (!m_listeners.add(new ComparableReference(listener))) { // throw new IllegalStateException(String.format( // "Internal Error: Listener '%s' can not be added more than once.", listener)); } } }
Example #12
Source File: RawRankProfile.java From vespa with Apache License 2.0 | 6 votes |
private void deriveRankingFeatures(RankProfile rankProfile, ModelContext.Properties deployProperties) { firstPhaseRanking = rankProfile.getFirstPhaseRanking(); secondPhaseRanking = rankProfile.getSecondPhaseRanking(); summaryFeatures = new LinkedHashSet<>(rankProfile.getSummaryFeatures()); rankFeatures = rankProfile.getRankFeatures(); rerankCount = rankProfile.getRerankCount(); matchPhaseSettings = rankProfile.getMatchPhaseSettings(); numThreadsPerSearch = rankProfile.getNumThreadsPerSearch(); minHitsPerThread = rankProfile.getMinHitsPerThread(); numSearchPartitions = rankProfile.getNumSearchPartitions(); termwiseLimit = rankProfile.getTermwiseLimit().orElse(deployProperties.defaultTermwiseLimit()); keepRankCount = rankProfile.getKeepRankCount(); rankScoreDropLimit = rankProfile.getRankScoreDropLimit(); ignoreDefaultRankFeatures = rankProfile.getIgnoreDefaultRankFeatures(); rankProperties = new ArrayList<>(rankProfile.getRankProperties()); derivePropertiesAndSummaryFeaturesFromFunctions(rankProfile.getFunctions()); }
Example #13
Source File: CameraXModule.java From mollyim-android with GNU General Public License v3.0 | 6 votes |
@RequiresPermission(permission.CAMERA) private Set<Integer> getAvailableCameraLensFacing() { // Start with all camera directions Set<Integer> available = new LinkedHashSet<>(Arrays.asList(LensFacingConverter.values())); // If we're bound to a lifecycle, remove unavailable cameras if (mCurrentLifecycle != null) { if (!hasCameraWithLensFacing(CameraSelector.LENS_FACING_BACK)) { available.remove(CameraSelector.LENS_FACING_BACK); } if (!hasCameraWithLensFacing(CameraSelector.LENS_FACING_FRONT)) { available.remove(CameraSelector.LENS_FACING_FRONT); } } return available; }
Example #14
Source File: StandardScalerModelInfoAdapter.java From spark-transformers with Apache License 2.0 | 6 votes |
@Override public StandardScalerModelInfo getModelInfo(final StandardScalerModel from) { final StandardScalerModelInfo modelInfo = new StandardScalerModelInfo(); modelInfo.setMean(from.mean().toArray()); modelInfo.setStd(from.std().toArray()); modelInfo.setWithMean(from.getWithMean()); modelInfo.setWithStd(from.getWithStd()); Set<String> inputKeys = new LinkedHashSet<String>(); inputKeys.add(from.getInputCol()); modelInfo.setInputKeys(inputKeys); Set<String> outputKeys = new LinkedHashSet<String>(); outputKeys.add(from.getOutputCol()); modelInfo.setOutputKeys(outputKeys); return modelInfo; }
Example #15
Source File: DefineResolver.java From needsmoredojo with Apache License 2.0 | 6 votes |
/** * gets a set of all define and require blocks from a given file. * * @param file * @return */ public Set<JSCallExpression> getAllImportBlocks(PsiFile file) { final Set<JSCallExpression> listOfDefinesOrRequiresToVisit = new LinkedHashSet<JSCallExpression>(); JSRecursiveElementVisitor defineOrRequireVisitor = new JSRecursiveElementVisitor() { @Override public void visitJSCallExpression(JSCallExpression expression) { if(expression != null && expression.getMethodExpression() != null && (expression.getMethodExpression().getText().equals("define") || expression.getMethodExpression().getText().equals("require"))) { listOfDefinesOrRequiresToVisit.add(expression); } super.visitJSCallExpression(expression); } }; file.accept(defineOrRequireVisitor); return listOfDefinesOrRequiresToVisit; }
Example #16
Source File: FacebookAccessTokenConverter.java From geowave with Apache License 2.0 | 6 votes |
@Override public OAuth2Authentication extractAuthentication(final Map<String, ?> map) { final Map<String, String> parameters = new HashMap<>(); final Set<String> scope = parseScopes(map); final Object principal = map.get("name"); final Authentication user = new UsernamePasswordAuthenticationToken(principal, "N/A", defaultAuthorities); final String clientId = (String) map.get(CLIENT_ID); parameters.put(CLIENT_ID, clientId); final Set<String> resourceIds = new LinkedHashSet<>( map.containsKey(AUD) ? (Collection<String>) map.get(AUD) : Collections.<String>emptySet()); final OAuth2Request request = new OAuth2Request(parameters, clientId, null, true, scope, resourceIds, null, null, null); return new OAuth2Authentication(request, user); }
Example #17
Source File: DefaultModuleRegistry.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 5 votes |
public DefaultModule(String name, Set<File> implementationClasspath, Set<File> runtimeClasspath, Set<Module> modules) { this.name = name; this.implementationClasspath = new DefaultClassPath(implementationClasspath); this.runtimeClasspath = new DefaultClassPath(runtimeClasspath); this.modules = modules; Set<File> classpath = new LinkedHashSet<File>(); classpath.addAll(implementationClasspath); classpath.addAll(runtimeClasspath); this.classpath = new DefaultClassPath(classpath); }
Example #18
Source File: OrientationManager.java From SpeedHud with Apache License 2.0 | 5 votes |
/** * Initializes a new instance of {@code OrientationManager}, using the specified context to * access system services. */ public OrientationManager(SensorManager sensorManager, LocationManager locationManager) { mRotationMatrix = new float[16]; mOrientation = new float[9]; mSensorManager = sensorManager; mLocationManager = locationManager; mListeners = new LinkedHashSet<OnChangedListener>(); }
Example #19
Source File: WebTermImportanceFilter.java From OpenEphyra with GNU General Public License v2.0 | 5 votes |
/** extract non lower case parts from the targets: * "the film 'Star Wars'" --> "'Star Wars'" * "1998 indictment and trial of Susan McDougal" --> "Susan McDougal" * "Miss Universe 2000 crowned" --> "Miss Universe 2000" * "Abraham from the bible" --> "Abraham" * "Gobi desert" --> "Gobi" * * @param targets the list of targets */ private void extractUpperCaseParts(ArrayList<String> targets) { HashSet<String> duplicateFreeTargets = new LinkedHashSet<String>(targets); for (Iterator<String> iter = duplicateFreeTargets.iterator(); iter.hasNext();) { String target = iter.next(); String[] targetTokens = target.split("\\s"); String upperCasePart = null; int i = 0; while (i < targetTokens.length) { // find start of next upper case part while ((i < targetTokens.length) && !Character.isUpperCase(targetTokens[i].charAt(0))) i++; // start upper case part if (i < targetTokens.length) { upperCasePart = targetTokens[i]; i++; } // collect non-lower-case part while ((i < targetTokens.length) && !Character.isLowerCase(targetTokens[i].charAt(0))) { upperCasePart += " " + targetTokens[i]; i++; } if (upperCasePart != null) { targets.add(upperCasePart); upperCasePart = null; } } } }
Example #20
Source File: AbstractLuceneIndexerImpl.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
protected static Set<String> deleteReference(Collection<String> nodeRefs, IndexReader reader, boolean delete) throws LuceneIndexException { Set<String> refs = new LinkedHashSet<String>(); for (String nodeRef : nodeRefs) { try { TermDocs td = reader.termDocs(new Term("PARENT", nodeRef)); while (td.next()) { int doc = td.doc(); Document document = reader.document(doc); String[] ids = document.getValues("ID"); refs.add(ids[ids.length - 1]); if (delete) { reader.deleteDocument(doc); } } td.close(); } catch (IOException e) { throw new LuceneIndexException("Failed to delete node by parent for " + nodeRef, e); } } return refs; }
Example #21
Source File: Log1PScalerModelInfoAdapter.java From spark-transformers with Apache License 2.0 | 5 votes |
@Override public Log1PScalerModelInfo getModelInfo(final Log1PScaler from, DataFrame df) { Log1PScalerModelInfo modelInfo = new Log1PScalerModelInfo(); Set<String> inputKeys = new LinkedHashSet<String>(); inputKeys.add(from.getInputCol()); modelInfo.setInputKeys(inputKeys); Set<String> outputKeys = new LinkedHashSet<String>(); outputKeys.add(from.getOutputCol()); modelInfo.setOutputKeys(outputKeys); return modelInfo; }
Example #22
Source File: FlinkExecutable.java From kylin-on-parquet-v2 with Apache License 2.0 | 5 votes |
private void attachSegmentsMetadataWithDict(List<CubeSegment> segments) throws IOException { Set<String> dumpList = new LinkedHashSet<>(); dumpList.addAll(JobRelatedMetaUtil.collectCubeMetadata(segments.get(0).getCubeInstance())); ResourceStore rs = ResourceStore.getStore(segments.get(0).getConfig()); for (CubeSegment segment : segments) { dumpList.addAll(segment.getDictionaryPaths()); if (rs.exists(segment.getStatisticsResourcePath())) { // cube statistics is not available for new segment dumpList.add(segment.getStatisticsResourcePath()); } } JobRelatedMetaUtil.dumpAndUploadKylinPropsAndMetadata(dumpList, (KylinConfigExt) segments.get(0).getConfig(), this.getParam(FlinkCubingByLayer.OPTION_META_URL.getOpt())); }
Example #23
Source File: CleaningAIRDJob.java From M2Doc with Eclipse Public License 1.0 | 5 votes |
/** * delete the representation. */ @Override public void run() { final Set<DRepresentationDescriptor> representations = new LinkedHashSet<DRepresentationDescriptor>(); representations.add(representation); session.getTransactionalEditingDomain().getCommandStack() .execute(new DeleteRepresentationCommand(session, representations)); }
Example #24
Source File: SmallestSequentialSubarrayTest.java From elements-of-programming-interviews-solutions with MIT License | 5 votes |
@Test public void findSubarray3() throws Exception { expected = new Tuple(3,7); paragraph = Arrays.asList( "Mark", "Steve", "Joan", "Steven", "Greg", "Jordan", "Mark", "Kevin", "Joan", "Daisy", "Greg", "Mark" ); keywords = new LinkedHashSet<>(Arrays.asList( "Steven", "Greg", "Jordan", "Mark", "Kevin" )); test(expected, paragraph, keywords); }
Example #25
Source File: ClassPathBeanDefinitionScanner.java From lams with GNU General Public License v2.0 | 5 votes |
/** * Perform a scan within the specified base packages, * returning the registered bean definitions. * <p>This method does <i>not</i> register an annotation config processor * but rather leaves this up to the caller. * @param basePackages the packages to check for annotated classes * @return set of beans registered if any for tooling registration purposes (never {@code null}) */ protected Set<BeanDefinitionHolder> doScan(String... basePackages) { Assert.notEmpty(basePackages, "At least one base package must be specified"); Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>(); for (String basePackage : basePackages) { Set<BeanDefinition> candidates = findCandidateComponents(basePackage); for (BeanDefinition candidate : candidates) { ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate); candidate.setScope(scopeMetadata.getScopeName()); String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry); if (candidate instanceof AbstractBeanDefinition) { postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName); } if (candidate instanceof AnnotatedBeanDefinition) { AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate); } if (checkCandidate(beanName, candidate)) { BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName); definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); beanDefinitions.add(definitionHolder); registerBeanDefinition(definitionHolder, this.registry); } } } return beanDefinitions; }
Example #26
Source File: Infer.java From hottub with GNU General Public License v2.0 | 5 votes |
/** * Retrieves all dependencies with given kind(s). */ protected Set<Node> getDependencies(DependencyKind... depKinds) { Set<Node> buf = new LinkedHashSet<Node>(); for (DependencyKind dk : depKinds) { Set<Node> depsByKind = deps.get(dk); if (depsByKind != null) { buf.addAll(depsByKind); } } return buf; }
Example #27
Source File: PropertyAuditFilterTest.java From alfresco-repository with GNU Lesser General Public License v3.0 | 5 votes |
@Test public void testNonStringValue() { LinkedHashSet<Integer> value = new LinkedHashSet<Integer>(); value.add(Integer.valueOf(1)); value.add(Integer.valueOf(2)); value.add(Integer.valueOf(3)); auditMap.put("name", value); properties.put("audit.filter.root.action.enabled", "true"); properties.put("audit.filter.root.action.name", "\\[1, 2, 3\\]"); boolean actual = filter.accept(rootPath, auditMap); assertTrue("The check should have worked on the value.toString().", actual); }
Example #28
Source File: BindBean2SharedPreferences.java From kripton with Apache License 2.0 | 5 votes |
/** * for attribute valueIntegerSet serialization */ protected String serializeValueIntegerSet(LinkedHashSet<Integer> value) { if (value==null) { return null; } KriptonJsonContext context=KriptonBinder.jsonBind(); try (KriptonByteArrayOutputStream stream=new KriptonByteArrayOutputStream(); JacksonWrapperSerializer wrapper=context.createSerializer(stream)) { JsonGenerator jacksonSerializer=wrapper.jacksonGenerator; jacksonSerializer.writeStartObject(); int fieldCount=0; if (value!=null) { fieldCount++; // write wrapper tag jacksonSerializer.writeFieldName("valueIntegerSet"); jacksonSerializer.writeStartArray(); for (Integer item: value) { if (item==null) { jacksonSerializer.writeNull(); } else { jacksonSerializer.writeNumber(item); } } jacksonSerializer.writeEndArray(); } jacksonSerializer.writeEndObject(); jacksonSerializer.flush(); return stream.toString(); } catch(Exception e) { e.printStackTrace(); throw(new KriptonRuntimeException(e.getMessage())); } }
Example #29
Source File: ScriptModuleSpec.java From Nicobar with Apache License 2.0 | 5 votes |
/** Build the {@link PathScriptArchive}. */ public ScriptModuleSpec build() { return new ScriptModuleSpec(moduleId, Collections.unmodifiableMap(new HashMap<String, Object>(archiveMetadata)), Collections.unmodifiableSet(new LinkedHashSet<ModuleId>(moduleDependencies)), Collections.unmodifiableSet(new LinkedHashSet<String>(compilerPluginIds)), appImportFilters != null ? Collections.unmodifiableSet(appImportFilters) : null, moduleImportFilters != null ? Collections.unmodifiableSet(moduleImportFilters) : null, moduleExportFilters != null ? Collections.unmodifiableSet(moduleExportFilters) : null); }
Example #30
Source File: SharedPrefUtils.java From EFRConnect-android with Apache License 2.0 | 5 votes |
public void addDeviceToFavorites(String device) { LinkedHashSet<String> favoritesDevices = getFavoritesDevices(); favoritesDevices.add(device); String json = gson.toJson(favoritesDevices); editor.putString(FAVORITES_DEVICES_KEY, json); editor.commit(); }