本文整理汇总了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;
}
示例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;
}
示例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();
}
示例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);
}
});
}
示例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;
}
示例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();
}
}
});
}
示例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();
}
示例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();
}
示例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);
}
示例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);
}
示例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();
}
}
示例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;
}
示例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);
});
}
示例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()))));
}
示例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);
}