@Test public void should_return_new_List() { ArrayList<String> list1 = Lists.newArrayList(); ArrayList<String> list2 = Lists.newArrayList(); assertThat(list2).isNotSameAs(list1); // be sure they have nothing in common list1.add("abc"); assertThat(list2).isEmpty(); }
private static List<String> loadLines(InputStream stream, Charset charset) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset)); boolean threw = true; try { List<String> strings = Lists.newArrayList(); String line = reader.readLine(); while (line != null) { strings.add(line); line = reader.readLine(); } threw = false; return strings; } finally { try { reader.close(); } catch (IOException e) { if (!threw) { throw e; // if there was an initial exception, don't hide it } } } }
/** * Searches the specified list for the specified object using the binary search algorithm. The * list must be sorted into ascending order according to the specified comparator (as by the * {@link Collections#sort(List, Comparator) Collections.sort(List, Comparator)} method), prior to * making this call. If it is not sorted, the results are undefined. * * <p>If there are elements in the list which compare as equal to the key, the choice of {@link * KeyPresentBehavior} decides which index is returned. If no elements compare as equal to the * key, the choice of {@link KeyAbsentBehavior} decides which index is returned. * * <p>This method runs in log(n) time on random-access lists, which offer near-constant-time * access to each list element. * * @param list the list to be searched. * @param key the value to be searched for. * @param comparator the comparator by which the list is ordered. * @param presentBehavior the specification for what to do if at least one element of the list * compares as equal to the key. * @param absentBehavior the specification for what to do if no elements of the list compare as * equal to the key. * @return the index determined by the {@code KeyPresentBehavior}, if the key is in the list; * otherwise the index determined by the {@code KeyAbsentBehavior}. */ public static <E> int binarySearch( List<? extends E> list, @Nullable E key, Comparator<? super E> comparator, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { checkNotNull(comparator); checkNotNull(list); checkNotNull(presentBehavior); checkNotNull(absentBehavior); if (!(list instanceof RandomAccess)) { list = Lists.newArrayList(list); } // TODO(user): benchmark when it's best to do a linear search int lower = 0; int upper = list.size() - 1; while (lower <= upper) { int middle = (lower + upper) >>> 1; int c = comparator.compare(key, list.get(middle)); if (c < 0) { upper = middle - 1; } else if (c > 0) { lower = middle + 1; } else { return lower + presentBehavior.resultIndex( comparator, key, list.subList(lower, upper + 1), middle - lower); } } return absentBehavior.resultIndex(lower); }
@Test public void should_return_empty_mutable_List() { ArrayList<String> list = Lists.newArrayList(); assertThat(list).isEmpty(); list.add("abc"); assertThat(list).containsExactly("abc"); }
class LecturerList { private List<LecturerContainer> lecturers = Lists.newArrayList(); public List<LecturerContainer> getLecturerContainterList() { return lecturers; } }
/** * A builder for creating immutable list instances, especially {@code public static final} lists * ("constant lists"). * * <p>Example: * * <pre>{@code * public static final ImmutableList<Color> GOOGLE_COLORS * = new ImmutableList.Builder<Color>() * .addAll(WEBSAFE_COLORS) * .add(new Color(0, 191, 255)) * .build(); * }</pre> * * <p>Builder instances can be reused - it is safe to call {@link #build} multiple times to build * multiple lists in series. Each new list contains the one created before it. */ public static class Builder<E> { private final ArrayList<E> contents = Lists.newArrayList(); /** * Creates a new builder. The returned builder is equivalent to the builder generated by {@link * ImmutableList#builder}. */ public Builder() {} /** * Adds {@code element} to the {@code ImmutableList}. * * @param element the element to add * @return this {@code Builder} object * @throws NullPointerException if {@code element} is null */ public Builder<E> add(E element) { Preconditions.checkNotNull(element, "element cannot be null"); contents.add(element); return this; } /** * Adds each element of {@code elements} to the {@code ImmutableList}. * * @param elements the {@code Iterable} to add to the {@code ImmutableList} * @return this {@code Builder} object * @throws NullPointerException if {@code elements} is or contains null */ public Builder<E> addAll(Iterable<? extends E> elements) { if (elements instanceof Collection) { @SuppressWarnings("unchecked") Collection<? extends E> collection = (Collection<? extends E>) elements; contents.ensureCapacity(contents.size() + collection.size()); } for (E elem : elements) { Preconditions.checkNotNull(elem, "elements contains a null"); contents.add(elem); } return this; } /** * Returns a newly-created {@code ImmutableList} based on the contents of the {@code Builder}. */ public ImmutableList<E> build() { return copyOf(contents); } }
/** * Returns an immutable list containing the given elements, in order. This method iterates over * {@code elements} at most once. Note that if {@code list} is a {@code List<String>}, then {@code * ImmutableList.copyOf(list)} returns an {@code ImmutableList<String>} containing each of the * strings in {@code list}, while ImmutableList.of(list)} returns an {@code * ImmutableList<List<String>>} containing one element (the given list itself). * * <p><b>Note:</b> Despite what the method name suggests, if {@code elements} is an {@code * ImmutableList}, no copy will actually be performed, and the given list itself will be returned. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableList<E> copyOf(Iterable<? extends E> elements) { if (elements instanceof ImmutableList) { /* * TODO: If the given ImmutableList is a sublist, copy the referenced * portion of the array into a new array to save space? */ @SuppressWarnings("unchecked") // all supported methods are covariant ImmutableList<E> list = (ImmutableList<E>) elements; return list; } else if (elements instanceof Collection) { @SuppressWarnings("unchecked") Collection<? extends E> coll = (Collection<? extends E>) elements; return copyOfInternal(coll); } else { return copyOfInternal(Lists.newArrayList(elements)); } }
public List<ContactItemInterface> parse(String jsonString) throws IOException { List<ContactItemInterface> result = Lists.newArrayList(); LecturerList list = null; list = getLecturerList(jsonString); if (list != null) { List<LecturerContainer> lecturers = list.getLecturerContainterList(); for (LecturerContainer lc : lecturers) { result.add(lc.getLecturer()); } } return result; }
private void initFieldWriters() throws IOException { fieldConverters = Lists.newArrayList(); try { int fieldId = 0; for (VectorWrapper w : batch) { if (w.getField().getPath().equalsIgnoreCase(WriterPrel.PARTITION_COMPARATOR_FIELD)) { continue; } FieldReader reader = w.getValueVector().getReader(); FieldConverter converter = getConverter(recordWriter, fieldId++, w.getField().getLastName(), reader); fieldConverters.add(converter); } } catch(Exception e) { logger.error("Failed to create FieldWriter.", e); throw new IOException("Failed to initialize FieldWriters.", e); } }
private Integer syncToSeriesGuide(ServiceManager manager, String username) { mResult = ""; List<TvShow> shows; try { // get watched episodes from trakt shows = manager.userService().libraryShowsWatched(username).extended(ExtendedParam.Min).fire(); } catch (TraktException e) { fireTrackerEventToSeriesGuide(e.getMessage()); Log.w(TAG, e); return FAILED_API; } catch (ApiException e) { fireTrackerEventToSeriesGuide(e.getMessage()); Log.w(TAG, e); return FAILED_API; } // get show ids in local database Cursor showTvdbIds = mContext .getContentResolver() .query(Shows.CONTENT_URI, new String[] {Shows._ID}, null, null, null); // assume we have a local list of which shows to sync (later...) while (showTvdbIds.moveToNext()) { String tvdbId = showTvdbIds.getString(0); for (TvShow tvShow : shows) { if (tvdbId.equalsIgnoreCase(tvShow.tvdbId)) { if (mResult.length() != 0) { mResult += ", "; } if (mIsSyncingUnseen) { ContentValues values = new ContentValues(); values.put(Episodes.WATCHED, false); mContext .getContentResolver() .update(Episodes.buildEpisodesOfShowUri(tvdbId), values, null, null); } final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // go through watched seasons, try to match them with local // season List<TvShowSeason> seasons = tvShow.seasons; for (TvShowSeason season : seasons) { Cursor seasonMatch = mContext .getContentResolver() .query( Seasons.buildSeasonsOfShowUri(tvdbId), new String[] {Seasons._ID}, Seasons.COMBINED + "=?", new String[] {season.season.toString()}, null); // if we found a season, go on with its episodes if (seasonMatch.moveToFirst()) { String seasonId = seasonMatch.getString(0); // build episodes update query to mark seen episodes for (Integer episode : season.episodes.numbers) { batch.add( ContentProviderOperation.newUpdate(Episodes.buildEpisodesOfSeasonUri(seasonId)) .withSelection(Episodes.NUMBER + "=?", new String[] {episode.toString()}) .withValue(Episodes.WATCHED, true) .build()); } } seasonMatch.close(); } // last chance to abort before doing work if (isCancelled()) { showTvdbIds.close(); return null; } try { mContext.getContentResolver().applyBatch(SeriesContract.CONTENT_AUTHORITY, batch); } catch (RemoteException e) { // Failed binder transactions aren't recoverable fireTrackerEventToSeriesGuide(e.getMessage()); throw new RuntimeException("Problem applying batch operation", e); } catch (OperationApplicationException e) { // Failures like constraint violation aren't // recoverable fireTrackerEventToSeriesGuide(e.getMessage()); throw new RuntimeException("Problem applying batch operation", e); } mResult += tvShow.title; // remove synced show shows.remove(tvShow); break; } } } showTvdbIds.close(); if (mResult.length() != 0) { return SUCCESS_WORK; } else { return SUCCESS_NOWORK; } }
/** * Returns an immutable list containing the given elements, in order. * * @throws NullPointerException if any of {@code elements} is null */ public static <E> ImmutableList<E> copyOf(Iterator<? extends E> elements) { return copyOfInternal(Lists.newArrayList(elements)); }
/** * Returns an iterable whose iterators cycle indefinitely over the provided elements. * * <p>After {@code remove} is invoked on a generated iterator, the removed element will no longer * appear in either that iterator or any other iterator created from the same source iterable. * That is, this method behaves exactly as {@code Iterables.cycle(Lists.newArrayList(elements))}. * The iterator's {@code hasNext} method returns {@code true} until all of the original elements * have been removed. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You * should use an explicit {@code break} or be certain that you will eventually remove all the * elements. * * <p>To cycle over the elements {@code n} times, use the following: {@code * Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))} */ public static <T> Iterable<T> cycle(T... elements) { return cycle(Lists.newArrayList(elements)); }
/** * Converts an iterable into a collection. If the iterable is already a collection, it is * returned. Otherwise, an {@link java.util.ArrayList} is created with the contents of the * iterable in the same iteration order. */ private static <E> Collection<E> toCollection(Iterable<E> iterable) { return (iterable instanceof Collection) ? (Collection<E>) iterable : Lists.newArrayList(iterable.iterator()); }
static { sListUrls = Lists.newArrayList(); }
@Test public void should_return_empty_List() { ArrayList<String> list = Lists.newArrayList(); assertThat(list).isEmpty(); }
public final void showSuccessfulInstallMessage(String paramString1, String paramString2, String paramString3, boolean paramBoolean) { hideInstallingMessage(); if (paramBoolean) { hideAllMessagesForPackage(paramString2); String str3 = (String)FinskyPreferences.successfulUpdateNotificationAppList.get(); String str4 = paramString1.replace('\n', ' '); ArrayList localArrayList; String str6; String str7; Resources localResources2; String str8; label265: Intent localIntent2; Intent localIntent3; if (TextUtils.isEmpty(str3)) { localArrayList = new ArrayList(); localArrayList.add(0, str4); String str5 = TextUtils.join("\n", localArrayList); FinskyPreferences.successfulUpdateNotificationAppList.put(str5); int i = localArrayList.size(); str6 = String.format(this.mContext.getString(2131362413), new Object[] { str4 }); Resources localResources1 = this.mContext.getResources(); Object[] arrayOfObject1 = new Object[1]; arrayOfObject1[0] = Integer.valueOf(i); str7 = localResources1.getQuantityString(2131296266, i, arrayOfObject1); localResources2 = this.mContext.getResources(); switch (i) { default: Object[] arrayOfObject6 = new Object[5]; arrayOfObject6[0] = localArrayList.get(0); arrayOfObject6[1] = localArrayList.get(1); arrayOfObject6[2] = localArrayList.get(2); arrayOfObject6[3] = localArrayList.get(3); arrayOfObject6[4] = Integer.valueOf(i - 4); str8 = localResources2.getString(2131362401, arrayOfObject6); if (i <= 1) { logNotificationImpression(902, null); } localIntent2 = NotificationReceiver.getSuccessfullyUpdatedClickedIntent(); localIntent3 = NotificationReceiver.getSuccessfullyUpdatedDeletedIntent(); if ((!SUPPORTS_RICH_NOTIFICATIONS) || (i <= 1)) { break; } } } for (int j = 2130838131;; j = 2130838130) { showNewNotification("successful update", str6, str7, str8, str8, j, null, -1, localIntent2, true, localIntent3); return; localArrayList = Lists.newArrayList(str3.split("\n")); localArrayList.remove(str4); break; FinskyLog.w("App count is 0 in successful update notification", new Object[0]); return; str8 = (String)localArrayList.get(0); break label265; Object[] arrayOfObject5 = new Object[2]; arrayOfObject5[0] = localArrayList.get(0); arrayOfObject5[1] = localArrayList.get(1); str8 = localResources2.getString(2131362338, arrayOfObject5); break label265; Object[] arrayOfObject4 = new Object[3]; arrayOfObject4[0] = localArrayList.get(0); arrayOfObject4[1] = localArrayList.get(1); arrayOfObject4[2] = localArrayList.get(2); str8 = localResources2.getString(2131362339, arrayOfObject4); break label265; Object[] arrayOfObject3 = new Object[4]; arrayOfObject3[0] = localArrayList.get(0); arrayOfObject3[1] = localArrayList.get(1); arrayOfObject3[2] = localArrayList.get(2); arrayOfObject3[3] = localArrayList.get(3); str8 = localResources2.getString(2131362340, arrayOfObject3); break label265; Object[] arrayOfObject2 = new Object[5]; arrayOfObject2[0] = localArrayList.get(0); arrayOfObject2[1] = localArrayList.get(1); arrayOfObject2[2] = localArrayList.get(2); arrayOfObject2[3] = localArrayList.get(3); arrayOfObject2[4] = localArrayList.get(4); str8 = localResources2.getString(2131362341, arrayOfObject2); break label265; } } String str1 = String.format(this.mContext.getString(2131362398), new Object[] { paramString1 }); String str2 = this.mContext.getString(2131362397); if (!TextUtils.isEmpty(paramString3)) { str2 = this.mContext.getString(2131362396); } logNotificationImpression(901, null); Intent localIntent1 = NotificationReceiver.getSuccessfullyInstalledClickedIntent(paramString2, paramString3); if (SUPPORTS_RICH_NOTIFICATIONS) {} for (;;) { try { PackageManager localPackageManager = this.mContext.getPackageManager(); if (Build.VERSION.SDK_INT >= 22) { localObject2 = localPackageManager.getApplicationInfo(paramString2, 1024).loadUnbadgedIcon(localPackageManager); Object localObject3 = null; if (localObject2 != null) { Bitmap localBitmap = drawableToBitmap((Drawable)localObject2, paramString2); localObject3 = localBitmap; } localObject1 = localObject3; showNewNotification(paramString2, str1, paramString1, str2, null, 2130838130, localObject1, 0, localIntent1, true, null); return; } Drawable localDrawable = localPackageManager.getApplicationIcon(paramString2); Object localObject2 = localDrawable; continue; Object localObject1 = null; } catch (Exception localException) {} } }