当前位置: 首页>>代码示例>>Java>>正文


Java Stream类代码示例

本文整理汇总了Java中com.annimon.stream.Stream的典型用法代码示例。如果您正苦于以下问题:Java Stream类的具体用法?Java Stream怎么用?Java Stream使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Stream类属于com.annimon.stream包,在下文中一共展示了Stream类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: performFiltering

import com.annimon.stream.Stream; //导入依赖的package包/类
@Override
protected FilterResults performFiltering(CharSequence charSequence) {

    //返回的results即为过滤后的ArrayList<City>
    FilterResults results = new FilterResults();

    //无约束字符串则返回null
    if (charSequence == null || charSequence.length() == 0) {
        results.values = null;
        results.count = 0;
    } else {
        String prefixString = charSequence.toString().toLowerCase();
        //新建Values存放过滤后的数据
        ArrayList<City> newValues = new ArrayList<>();
        Stream.of(cities)
                .filter(city -> (city.getCityName().contains(prefixString)
                        || city.getCityNameEn().contains(prefixString) || city.getParent().contains(prefixString)
                        || city.getRoot().contains(prefixString)))
                .forEach(newValues::add);
        results.values = newValues;
        results.count = newValues.size();
    }
    return results;
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:25,代码来源:CityListAdapter.java

示例2: getMonthAvgScore

import com.annimon.stream.Stream; //导入依赖的package包/类
public LinkedHashMap<Integer, Double> getMonthAvgScore() {
    Calendar date = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
    date.setTimeInMillis(getFirstTimestamp());
    Calendar now = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC"));
    LinkedHashMap<Integer, Double> monthsAvgScore = new LinkedHashMap<>();
    HashMap<Integer, List<Poem>> monthsPoems = new HashMap<>();

    while (totalMonths(date) <= totalMonths(now)) {
        monthsAvgScore.put(totalMonths(date), 0d);
        monthsPoems.put(totalMonths(date), new ArrayList<>());
        date.add(Calendar.MONTH, 1);
    }

    int pkey;
    for (Poem p : poems) {
        date.setTimeInMillis(p.timestamp_long);
        pkey = totalMonths(date);
        monthsPoems.get(pkey).add(p);
    }
    for (int key : monthsPoems.keySet()) {
        monthsAvgScore.put(key, Stream.of(monthsPoems.get(key))
                .mapToDouble(p -> p.score).sum() / monthsPoems.get(key).size());
    }
    return monthsAvgScore;
}
 
开发者ID:PaulKlinger,项目名称:Sprog-App,代码行数:26,代码来源:PoemStatistics.java

示例3: ExposedMethod

import com.annimon.stream.Stream; //导入依赖的package包/类
public ExposedMethod(Element element) {
    ExecutableType method = (ExecutableType) element.asType();
    TypeElement declaringClass = (TypeElement) element.getEnclosingElement();
    this.name = element.getSimpleName().toString();
    this.originalMethod = declaringClass.getQualifiedName().toString() + "." + element.getSimpleName();
    this.returnType = method.getReturnType().toString();
    this.params = new ArrayList<>();
    int count = 0;
    for (TypeMirror param : method.getParameterTypes()) {
        this.params.add(param.toString());
        String[] components = param.toString().toLowerCase().split("\\.");
        String paramName = components[components.length - 1];
        if (paramName.endsWith(">")) {
            paramName = paramName.substring(0, paramName.length() - 1);
        }
        this.params.add(paramName + count);
        count++;
    }
    this.thrown = Stream.of(method.getThrownTypes()).map(new Function<TypeMirror, String>() {
        @Override
        public String apply(TypeMirror typeMirror) {
            return typeMirror.toString();
        }
    }).toList();
}
 
开发者ID:globulus,项目名称:easyprefs,代码行数:26,代码来源:ExposedMethod.java

示例4: loadIcon

import com.annimon.stream.Stream; //导入依赖的package包/类
private void loadIcon(ImageView dayIcon, Calendar day) {
    if (mCalendarProperties.getEventDays() == null || mCalendarProperties.getCalendarType() != CalendarView.CLASSIC) {
        dayIcon.setVisibility(View.GONE);
        return;
    }

    Stream.of(mCalendarProperties.getEventDays()).filter(eventDate ->
            eventDate.getCalendar().equals(day)).findFirst().executeIfPresent(eventDay -> {

        ImageUtils.loadResource(dayIcon, eventDay.getImageResource());

        // If a day doesn't belong to current month then image is transparent
        if (!isCurrentMonthDay(day) || !isActiveDay(day)) {
            dayIcon.setAlpha(0.12f);
        }

    });
}
 
开发者ID:Applandeo,项目名称:Material-Calendar-View,代码行数:19,代码来源:CalendarDayAdapter.java

示例5: doInBackground

import com.annimon.stream.Stream; //导入依赖的package包/类
@Override
@SafeVarargs
protected final List<T> doInBackground(Predicate<T>... params) {
    if(!isCancelled()) {
        if(comparator == null)
            return Stream.of(model)
                    .filter(params[0])
                    .toList();
        else
            return Stream.of(model)
                    .filter(params[0])
                    .sorted(comparator)
                    .toList();
    }
    return null;
}
 
开发者ID:wax911,项目名称:anitrend-app,代码行数:17,代码来源:FilterBackgroundTask.java

示例6: onClick

import com.annimon.stream.Stream; //导入依赖的package包/类
@Override
public void onClick(View v) {
    if (!(v instanceof KeyView)) {
        return;
    }
    KeyView keyView = (KeyView) v;
    final KeyEntry key = keyView.getBoundKey();
    Stream.of(mKeyboardCallbacks).forEach(new Consumer<KeyboardCallback>() {
        @Override
        public void accept(KeyboardCallback callback) {
            if (key.keyType == KeyType.GENERAL) {
                callback.onTextKey(key.text);
            } else if (key.keyType == KeyType.DELETE) {
                callback.onDeleteKey();
            } else if (key.keyType == KeyType.OK) {
                callback.onConfirmKey();
            }
        }
    });
}
 
开发者ID:parkingwang,项目名称:vehicle-keyboard-android,代码行数:21,代码来源:KeyboardView.java

示例7: onOpen

import com.annimon.stream.Stream; //导入依赖的package包/类
@Override
public void onOpen() {
	changeConnectionState(CONNECTED);
	startCheckHandler();
	sendConnect();

	// send all pending (unsent) messages
	if(mAuth.isAuthPending() || mAuth.isAuthRequired()) {
		mAuth.setAuthPending();
		sendAuthMessage();
	}

	if(mAuth.isDeauthPending()) sendDeauthMessage();

	Stream.of(mPendingMessageList).forEach(this::sendMessage);
	mPendingMessageList.clear();
}
 
开发者ID:rapid-io,项目名称:rapid-io-android,代码行数:18,代码来源:WebSocketRapidConnection.java

示例8: handleErrMessage

import com.annimon.stream.Stream; //导入依赖的package包/类
private synchronized void handleErrMessage(@NonNull Message.Err message) {
	switch(message.getType()) {
		case CONNECTION_TERMINATED:
			disconnectWebSocketConnection(false);
			mExecutor.doOnMain(() ->
			{
				createWebSocketConnectionIfNeeded();
				mSubscriptionCount = 0;
				reconnectSubscriptions();
			});
			break;
		default:
			MessageFuture sentMessage = Stream.of(mSentMessageList).filter(m -> message.getEventId().equals(m.getMessage().getEventId())).findFirst().orElse(null);
			if(sentMessage != null) {
				RapidError error = new RapidError(RapidError.ErrorType.fromServerError(message, sentMessage));
				mLogger.logE(error);
				sentMessage.getRapidFuture().invokeError(error);
				updateCountersOnError(sentMessage);
				mSentMessageList.remove(sentMessage);
			}

			break;
	}

	disconnectWebSocketConnectionIfNeeded();
}
 
开发者ID:rapid-io,项目名称:rapid-io-android,代码行数:27,代码来源:WebSocketRapidConnection.java

示例9: onCreate

import com.annimon.stream.Stream; //导入依赖的package包/类
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mRecyclerView = findViewById(R.id.recyclerView);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
            LinearLayoutManager.VERTICAL));
    mAutoAdapter = AutoAdapterFactory.createAutoAdapter();
    mAutoAdapter.clicks(FootballerRenderer.class)
            .map(itemInfo -> itemInfo.renderer)
            .map(renderer -> renderer.footballerModel)
            .subscribe(footballerModel ->
                    Toast.makeText(this,
                            footballerModel.getName(), Toast.LENGTH_LONG)
                            .show());
    mAutoAdapter.clicks(FootballerRenderer.class, R.id.ivDelete)
            .map(itemInfo -> itemInfo.position)
            .subscribe(position -> {
                mAutoAdapter.remove(position);
                mAutoAdapter.notifyItemRemoved(position);
            });
    mAutoAdapter.addAll(Stream.of(getFootballers()).map(FootballerRenderer::new)
            .collect(Collectors.toList()));
    mRecyclerView.setAdapter(mAutoAdapter);
}
 
开发者ID:Zuluft,项目名称:AutoAdapter,代码行数:27,代码来源:SimpleSampleActivity.java

示例10: onCreate

import com.annimon.stream.Stream; //导入依赖的package包/类
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mRecyclerView = findViewById(R.id.recyclerView);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
            LinearLayoutManager.VERTICAL));
    mSortedAutoAdapter = AutoAdapterFactory.createSortedAutoAdapter();
    mSortedAutoAdapter.clicks(FootballerOrderableRenderer.class)
            .map(itemInfo -> itemInfo.renderer)
            .map(renderer -> renderer.footballerModel)
            .subscribe(footballerModel ->
                    Toast.makeText(this,
                            footballerModel.getName(), Toast.LENGTH_LONG)
                            .show());
    mSortedAutoAdapter.clicks(FootballerOrderableRenderer.class, R.id.ivDelete)
            .map(itemInfo -> itemInfo.position)
            .subscribe(position ->
                    mSortedAutoAdapter.remove(position));
    mSortedAutoAdapter.updateAll(Stream.of(getFootballers())
            .map(FootballerOrderableRenderer::new)
            .collect(Collectors.toList()));
    mRecyclerView.setAdapter(mSortedAutoAdapter);
}
 
开发者ID:Zuluft,项目名称:AutoAdapter,代码行数:26,代码来源:SortedAutoAdapterSampleActivity.java

示例11: checkListSizeTest

import com.annimon.stream.Stream; //导入依赖的package包/类
protected void checkListSizeTest(@NonNull RecyclerViewItemsTestData testData) {
  RequestMatcher requestMatcher = null;
  if (testData.getServiceUrl() != null) {
    requestMatcher = pathContains("/" + testData.getServiceUrl());
    RESTMockServer
        .whenGET(requestMatcher)
        .thenReturnFile(testData.getJsonResponsePath());
  }

  getActivityTestRule().launchActivity(testData.getIntent());

  Stream.of(testData.getContent())
      .forEach(item ->
          onView(allOf(isAssignableFrom(RecyclerView.class),
              anyOf(withId(item.first), isDescendantOfA(withId(item.first)))))
              .check(matches(countIs(item.second)))
      );

  if (requestMatcher != null) {
    RequestsVerifier.verifyGET(requestMatcher).invoked();
  }
}
 
开发者ID:xmartlabs,项目名称:bigbang,代码行数:23,代码来源:SingleActivityWithRecyclerViewInstrumentationTest.java

示例12: addItems

import com.annimon.stream.Stream; //导入依赖的package包/类
/**
 * Adds items to the data for the recycler view and notifies any registered observers that the items has been added.
 *
 * @param type  The type of the items.
 * @param items the items that will be the data for the recycler view.
 * @return if item was successfully added.
 */
@MainThread
protected <T extends RecycleItemType> boolean addItems(@NonNull T type, @Nullable List<?> items) {
  if (CollectionHelper.isNullOrEmpty(items)) {
    return false;
  }
  int lastItemCount = getItemCount();
  Stream.ofNullable(items)
      .forEach(item -> addItemWithoutNotifying(type, item, false));
  addItemTypeIfNeeded(type);
  if (lastItemCount == 0) {
    notifyDataSetChanged();
  } else {
    notifyItemRangeInserted(lastItemCount, getItemCount() - lastItemCount);
  }
  return true;
}
 
开发者ID:xmartlabs,项目名称:bigbang,代码行数:24,代码来源:BaseRecyclerViewAdapter.java

示例13: setItems

import com.annimon.stream.Stream; //导入依赖的package包/类
/**
 * Sets the items data for the recycler view and notifying any registered observers that the data set has
 * changed. It uses a function that calculates the difference between the old and the new items
 * in order to improve the update process.
 *
 * @param type                      Type of items.
 * @param newItems                  The items tobe added.
 * @param areItemsTheSameFunction   A function which checks that two items are the same.
 * @param areContentTheSameFunction A function which checks that the content of two items are the same.
 */
@SuppressWarnings("WeakerAccess")
protected <T, R extends RecycleItemType> void setItems(@NonNull R type, final @Nullable List<T> newItems,
                                                       @NonNull BiFunction<T, T, Boolean> areItemsTheSameFunction,
                                                       @NonNull BiFunction<T, T, Boolean> areContentTheSameFunction) {
  if (CollectionHelper.isNullOrEmpty(newItems)) {
    clearAll();
    return;
  }

  if (updateElementsDisposable != null && !updateElementsDisposable.isDisposed()) {
    updateElementsDisposable.dispose();
  }
  updateElementsDisposable = Single.fromCallable(() -> DiffUtil
      .calculateDiff(getUpdateDiffCallback(newItems, areItemsTheSameFunction, areContentTheSameFunction)))
      .subscribeOn(Schedulers.io())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribe(diffResult -> {
        items.clear();
        Stream.of(newItems)
            .forEach(item -> addItemWithoutNotifying(type, item, false));
        addItemTypeIfNeeded(type);
        diffResult.dispatchUpdatesTo(this);
      });
}
 
开发者ID:xmartlabs,项目名称:bigbang,代码行数:35,代码来源:BaseRecyclerViewAdapter.java

示例14: testSetItems

import com.annimon.stream.Stream; //导入依赖的package包/类
@Test
public void testSetItems() {
  List<Brand> brands = getBrands();

  MultipleItemActivity activity = mActivityRule.getActivity();
  activity.runOnUiThread(() -> activity.setItems(brands));

  checkRecyclerViewCondition(RecyclerViewAssertions.countIs(6));
  Stream.of(brands)
      .flatMap(brand -> Stream.concat(
          Stream.of(brand.getName()),
          Stream.ofNullable(brand.getCars()).map(Car::getModel)))
      .indexed()
      .forEach(carIntPair -> checkRecyclerViewCondition(
          RecyclerViewAssertions.atPosition(carIntPair.getFirst(), withText(carIntPair.getSecond()))));
}
 
开发者ID:xmartlabs,项目名称:bigbang,代码行数:17,代码来源:MultipleItemRecyclerViewTest.java

示例15: testRemoveOneItemWithMultipleInstance

import com.annimon.stream.Stream; //导入依赖的package包/类
@Test
public void testRemoveOneItemWithMultipleInstance() {
  Car carToRemove = new Car("New Car");
  List<Car> cars = getCarList();
  cars.add(carToRemove);
  cars.add(2, carToRemove);
  cars.add(5, carToRemove);

  SingleItemActivity activity = activityRule.getActivity();
  CarAdapter activityCarAdapter = activity.getAdapter();
  activity.runOnUiThread(() -> activityCarAdapter.setItems(cars));
  checkItems(cars);

  activity.runOnUiThread(() -> activityCarAdapter.removeItem(carToRemove));
  List<Car> newCards = Stream.of(cars)
      .filterNot(car -> Objects.equals(car, carToRemove))
      .toList();
  checkItems(newCards);
}
 
开发者ID:xmartlabs,项目名称:bigbang,代码行数:20,代码来源:SimpleItemTestRemoveItems.java


注:本文中的com.annimon.stream.Stream类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。