com.annimon.stream.Collectors Java Examples

The following examples show how to use com.annimon.stream.Collectors. 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: IntStreamMatcherTest.java    From Lightweight-Stream-API with Apache License 2.0 6 votes vote down vote up
@Test
public void testElements() {
    final IntStream stream = IntStream.of(-813, 123456, Short.MAX_VALUE);
    final Integer[] expected = new Integer[] {-813, 123456, (int) Short.MAX_VALUE};
    final Matcher<IntStream> matcher = elements(arrayContaining(expected));
    assertThat(stream, matcher);
    assertTrue(matcher.matches(stream));

    assertFalse(elements(arrayContaining(expected)).matches(IntStream.empty()));

    assertThat(matcher, description(allOf(
            containsString("IntStream elements"),
            containsString(Stream.of(expected)
                    .map(new Function<Integer, String>() {
                        @Override
                        public String apply(Integer t) {
                            return String.format("<%s>", t.toString());
                        }
                    })
                    .collect(Collectors.joining(", ")))
    )));
}
 
Example #2
Source File: SortedAutoAdapterSampleActivity.java    From AutoAdapter with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: SimpleSampleActivity.java    From AutoAdapter with Apache License 2.0 6 votes vote down vote up
@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.longClicks(FootballerRenderer.class)
            .map(itemInfo -> itemInfo.renderer)
            .map(renderer -> renderer.footballerModel)
            .subscribe(footballerModel ->
                    Toast.makeText(this,
                            footballerModel.getName(), Toast.LENGTH_LONG)
                            .show());
    mAutoAdapter.longClicks(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);
}
 
Example #4
Source File: LongStreamMatcherTest.java    From Lightweight-Stream-API with Apache License 2.0 6 votes vote down vote up
@Test
public void testElements() {
    final LongStream stream = LongStream.of(-813, 123456, Integer.MAX_VALUE);
    final Long[] expected = new Long[] {-813L, 123456L, (long) Integer.MAX_VALUE};
    final Matcher<LongStream> matcher = elements(arrayContaining(expected));
    assertThat(stream, matcher);
    assertTrue(matcher.matches(stream));

    assertFalse(elements(arrayContaining(expected)).matches(LongStream.empty()));

    assertThat(matcher, description(allOf(
            containsString("LongStream elements"),
            containsString(Stream.of(expected)
                    .map(new Function<Long, String>() {
                        @Override
                        public String apply(Long t) {
                            return String.format("<%sL>", t.toString());
                        }
                    })
                    .collect(Collectors.joining(", ")))
    )));
}
 
Example #5
Source File: DoubleStreamMatcherTest.java    From Lightweight-Stream-API with Apache License 2.0 6 votes vote down vote up
@Test
public void testElements() {
    final DoubleStream stream = DoubleStream.of(-0.987, 1.234, Math.PI, 1.618);
    final Double[] expected = new Double[] {-0.987, 1.234, Math.PI, 1.618};
    final Matcher<DoubleStream> matcher = elements(arrayContaining(expected));
    assertThat(stream, matcher);
    assertTrue(matcher.matches(stream));

    assertFalse(elements(arrayContaining(expected)).matches(DoubleStream.empty()));

    assertThat(matcher, description(allOf(
            containsString("DoubleStream elements"),
            containsString(Stream.of(expected)
                    .map(new Function<Double, String>() {
                        @Override
                        public String apply(Double t) {
                            return String.format("<%s>", t.toString());
                        }
                    })
                    .collect(Collectors.joining(", ")))
    )));
}
 
Example #6
Source File: IntStreamMatcherTest.java    From Lightweight-Stream-API with Apache License 2.0 6 votes vote down vote up
@Test
public void testElements() {
    final IntStream stream = IntStream.of(-813, 123456, Short.MAX_VALUE);
    final Integer[] expected = new Integer[] {-813, 123456, (int) Short.MAX_VALUE};
    final Matcher<IntStream> matcher = elements(arrayContaining(expected));
    assertThat(stream, matcher);
    assertTrue(matcher.matches(stream));

    assertFalse(elements(arrayContaining(expected)).matches(IntStream.empty()));

    assertThat(matcher, description(allOf(
            containsString("IntStream elements"),
            containsString(Stream.of(expected)
                    .map(new Function<Integer, String>() {
                        @Override
                        public String apply(Integer t) {
                            return String.format("<%s>", t.toString());
                        }
                    })
                    .collect(Collectors.joining(", ")))
    )));
}
 
Example #7
Source File: AbstractDeviceActivity.java    From openwebnet-android with MIT License 6 votes vote down vote up
protected void initSpinnerEnvironment() {
    environmentService.findAll().subscribe(environments -> {
        environmentArray = initSparseArray(environments);

        List<String> environmentValues = Stream.of(environments)
            .map(environment -> environment.getName()).collect(Collectors.toList());

        initEmptyList(environmentValues, labelNone);
        initSpinnerAdapter(spinnerDeviceEnvironment, environmentValues);

        int defaultEnvironment = getIntent().getIntExtra(EXTRA_DEFAULT_ENVIRONMENT, -1);
        log.debug("defaultEnvironment: {}", defaultEnvironment);
        if (defaultEnvironment >= MENU_ENVIRONMENT_RANGE_MIN && defaultEnvironment <= MENU_ENVIRONMENT_RANGE_MAX) {
            selectEnvironment(defaultEnvironment);
        }
    });
}
 
Example #8
Source File: AbstractDeviceActivity.java    From openwebnet-android with MIT License 6 votes vote down vote up
protected void initSpinnerGateway() {
    gatewayService.findAll().subscribe(gateways -> {
        gatewayArray = initSparseArray(gateways);

        List<String> gatewayValues = Stream.of(gateways)
            .map(gateway -> {
                String gatewayStr = String.format("%s:%d", gateway.getHost(), gateway.getPort());
                if (gateway.getPasswordNullable() != null) {
                    return gatewayStr.concat(" (*)");
                }
                return gatewayStr;
            }).collect(Collectors.toList());

        initEmptyList(gatewayValues, labelMissingGateway);
        initSpinnerAdapter(spinnerDeviceGateway, gatewayValues);

        String defaultGateway = getIntent().getStringExtra(EXTRA_DEFAULT_GATEWAY);
        log.debug("defaultGateway: {}", defaultGateway);
        if (defaultGateway != null) {
            selectGateway(defaultGateway);
        }
    });
}
 
Example #9
Source File: MarkReadReceiver.java    From bcm-android with GNU General Public License v3.0 6 votes vote down vote up
public static void process(@NonNull Context context,
                           @NonNull AccountContext accountContext,
                           @NonNull List<MarkedMessageInfo> markedReadMessages) {
    if (markedReadMessages.isEmpty()) return;

    List<SyncMessageId> syncMessageIds = new LinkedList<>();

    for (MarkedMessageInfo messageInfo : markedReadMessages) {
        scheduleDeletion(accountContext, messageInfo.getExpirationInfo());
        syncMessageIds.add(messageInfo.getSyncMessageId());
    }

    JobManager mgr = AmeModuleCenter.INSTANCE.accountJobMgr(accountContext);
    //todo multi device read state sync

    Map<Address, List<SyncMessageId>> addressMap = Stream.of(markedReadMessages)
            .map(MarkedMessageInfo::getSyncMessageId)
            .collect(Collectors.groupingBy(SyncMessageId::getAddress));

    for (Address address : addressMap.keySet()) {
        List<Long> timestamps = Stream.of(addressMap.get(address)).map(SyncMessageId::getTimetamp).toList();
        if (null != mgr) {
            mgr.add(new SendReadReceiptJob(context, accountContext, address, timestamps));
        }
    }
}
 
Example #10
Source File: TypingStatusRepository.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void notifyThread(long threadId, @NonNull Set<Typist> typists, boolean isReplacedByIncomingMessage) {
  Log.d(TAG, "notifyThread() threadId: " + threadId + "  typists: " + typists.size() + "  isReplaced: " + isReplacedByIncomingMessage);

  MutableLiveData<TypingState> notifier = Util.getOrDefault(notifiers, threadId, new MutableLiveData<>());
  notifiers.put(threadId, notifier);

  Set<Recipient> uniqueTypists = new LinkedHashSet<>();
  for (Typist typist : typists) {
    uniqueTypists.add(typist.getAuthor());
  }

  notifier.postValue(new TypingState(new ArrayList<>(uniqueTypists), isReplacedByIncomingMessage));

  Set<Long> activeThreads = Stream.of(typistMap.keySet()).filter(t -> !typistMap.get(t).isEmpty()).collect(Collectors.toSet());
  threadsNotifier.postValue(activeThreads);
}
 
Example #11
Source File: FastJobStorage.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public synchronized @NonNull List<DependencySpec> getDependencySpecsThatDependOnJob(@NonNull String jobSpecId) {
  List<DependencySpec> layer = getSingleLayerOfDependencySpecsThatDependOnJob(jobSpecId);
  List<DependencySpec> all   = new ArrayList<>(layer);

  Set<String> activeJobIds;

  do {
    activeJobIds = Stream.of(layer).map(DependencySpec::getJobId).collect(Collectors.toSet());
    layer.clear();

    for (String activeJobId : activeJobIds) {
      layer.addAll(getSingleLayerOfDependencySpecsThatDependOnJob(activeJobId));
    }

    all.addAll(layer);
  } while (!layer.isEmpty());

  return all;
}
 
Example #12
Source File: FastJobStorage.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void updateJobs(@NonNull List<JobSpec> jobSpecs) {
  jobDatabase.updateJobs(jobSpecs);

  Map<String, JobSpec>  updates = Stream.of(jobSpecs).collect(Collectors.toMap(JobSpec::getId));
  ListIterator<JobSpec> iter    = jobs.listIterator();

  while (iter.hasNext()) {
    JobSpec existing = iter.next();
    JobSpec update   = updates.get(existing.getId());

    if (update != null) {
      iter.set(update);
    }
  }
}
 
Example #13
Source File: PushProcessMessageJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private static Optional<List<LinkPreview>> getLinkPreviews(Optional<List<Preview>> previews, @NonNull String message) {
  if (!previews.isPresent()) return Optional.absent();

  List<LinkPreview> linkPreviews = new ArrayList<>(previews.get().size());

  for (Preview preview : previews.get()) {
    Optional<Attachment> thumbnail     = PointerAttachment.forPointer(preview.getImage());
    Optional<String>     url           = Optional.fromNullable(preview.getUrl());
    Optional<String>     title         = Optional.fromNullable(preview.getTitle());
    boolean              hasContent    = !TextUtils.isEmpty(title.or("")) || thumbnail.isPresent();
    boolean              presentInBody = url.isPresent() && Stream.of(LinkPreviewUtil.findWhitelistedUrls(message)).map(Link::getUrl).collect(Collectors.toSet()).contains(url.get());
    boolean              validDomain   = url.isPresent() && LinkPreviewUtil.isWhitelistedLinkUrl(url.get());

    if (hasContent && presentInBody && validDomain) {
      LinkPreview linkPreview = new LinkPreview(url.get(), title.or(""), thumbnail);
      linkPreviews.add(linkPreview);
    } else {
      Log.w(TAG, String.format("Discarding an invalid link preview. hasContent: %b presentInBody: %b validDomain: %b", hasContent, presentInBody, validDomain));
    }
  }

  return Optional.of(linkPreviews);
}
 
Example #14
Source File: PushProcessMessageJob.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private void updateGroupReceiptStatus(@NonNull SentTranscriptMessage message, long messageId, @NonNull GroupId groupString) {
  GroupReceiptDatabase      receiptDatabase   = DatabaseFactory.getGroupReceiptDatabase(context);
  List<Recipient>           messageRecipients = Stream.of(message.getRecipients()).map(address -> Recipient.externalPush(context, address)).toList();
  List<Recipient>           members           = DatabaseFactory.getGroupDatabase(context).getGroupMembers(groupString, GroupDatabase.MemberSet.FULL_MEMBERS_EXCLUDING_SELF);
  Map<RecipientId, Integer> localReceipts     = Stream.of(receiptDatabase.getGroupReceiptInfo(messageId))
                                                      .collect(Collectors.toMap(GroupReceiptInfo::getRecipientId, GroupReceiptInfo::getStatus));

  for (Recipient messageRecipient : messageRecipients) {
    //noinspection ConstantConditions
    if (localReceipts.containsKey(messageRecipient.getId()) && localReceipts.get(messageRecipient.getId()) < GroupReceiptDatabase.STATUS_UNDELIVERED) {
      receiptDatabase.update(messageRecipient.getId(), messageId, GroupReceiptDatabase.STATUS_UNDELIVERED, message.getTimestamp());
    } else if (!localReceipts.containsKey(messageRecipient.getId())) {
      receiptDatabase.insert(Collections.singletonList(messageRecipient.getId()), messageId, GroupReceiptDatabase.STATUS_UNDELIVERED, message.getTimestamp());
    }
  }

  List<org.whispersystems.libsignal.util.Pair<RecipientId, Boolean>> unidentifiedStatus = Stream.of(members)
                                                                                                .map(m -> new org.whispersystems.libsignal.util.Pair<>(m.getId(), message.isUnidentified(m.requireServiceId())))
                                                                                                .toList();
  receiptDatabase.setUnidentified(unidentifiedStatus, messageId);
}
 
Example #15
Source File: ObjectBoxDB.java    From Hentoid with Apache License 2.0 6 votes vote down vote up
Map<StatusContent, ImmutablePair<Integer, Long>> countProcessedImagesById(long contentId) {
    QueryBuilder<ImageFile> imgQuery = store.boxFor(ImageFile.class).query();
    imgQuery.equal(ImageFile_.contentId, contentId);
    List<ImageFile> images = imgQuery.build().find();

    Map<StatusContent, ImmutablePair<Integer, Long>> result = new EnumMap<>(StatusContent.class);
    // SELECT field, COUNT(*) GROUP BY (field) is not implemented in ObjectBox v2.3.1
    // (see https://github.com/objectbox/objectbox-java/issues/422)
    // => Group by and count have to be done manually (thanks God Stream exists !)
    // Group and count by type
    Map<StatusContent, List<ImageFile>> map = Stream.of(images).collect(Collectors.groupingBy(ImageFile::getStatus));
    for (Map.Entry<StatusContent, List<ImageFile>> entry : map.entrySet()) {
        StatusContent t = entry.getKey();
        int count = 0;
        long size = 0;
        if (entry.getValue() != null) {
            count = entry.getValue().size();
            for (ImageFile img : entry.getValue()) size += img.getSize();
        }
        result.put(t, new ImmutablePair<>(count, size));
    }

    return result;
}
 
Example #16
Source File: DirectoryHelperV1.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@SuppressLint("CheckResult")
private static @NonNull List<RecipientId> refreshDirectory(@NonNull Context context, @NonNull SignalServiceAccountManager accountManager) throws IOException {
  if (TextUtils.isEmpty(TextSecurePreferences.getLocalNumber(context))) {
    return Collections.emptyList();
  }

  if (!Permissions.hasAll(context, Manifest.permission.WRITE_CONTACTS)) {
    return Collections.emptyList();
  }

  RecipientDatabase recipientDatabase                       = DatabaseFactory.getRecipientDatabase(context);
  Set<String>       allRecipientNumbers                     = recipientDatabase.getAllPhoneNumbers();
  Stream<String>    eligibleRecipientDatabaseContactNumbers = Stream.of(allRecipientNumbers);
  Stream<String>    eligibleSystemDatabaseContactNumbers    = Stream.of(ContactAccessor.getInstance().getAllContactsWithNumbers(context));
  Set<String>       eligibleContactNumbers                  = Stream.concat(eligibleRecipientDatabaseContactNumbers, eligibleSystemDatabaseContactNumbers).collect(Collectors.toSet());
  Set<String>       storedNumbers                           = Stream.of(allRecipientNumbers).collect(Collectors.toSet());
  DirectoryResult   directoryResult                         = getDirectoryResult(context, accountManager, recipientDatabase, storedNumbers, eligibleContactNumbers);

  return directoryResult.getNewlyActiveRecipients();
}
 
Example #17
Source File: DoubleStreamMatcherTest.java    From Lightweight-Stream-API with Apache License 2.0 6 votes vote down vote up
@Test
public void testElements() {
    final DoubleStream stream = DoubleStream.of(-0.987, 1.234, Math.PI, 1.618);
    final Double[] expected = new Double[] {-0.987, 1.234, Math.PI, 1.618};
    final Matcher<DoubleStream> matcher = elements(arrayContaining(expected));
    assertThat(stream, matcher);
    assertTrue(matcher.matches(stream));

    assertFalse(elements(arrayContaining(expected)).matches(DoubleStream.empty()));

    assertThat(matcher, description(allOf(
            containsString("DoubleStream elements"),
            containsString(Stream.of(expected)
                    .map(new Function<Double, String>() {
                        @Override
                        public String apply(Double t) {
                            return String.format("<%s>", t.toString());
                        }
                    })
                    .collect(Collectors.joining(", ")))
    )));
}
 
Example #18
Source File: LongStreamMatcherTest.java    From Lightweight-Stream-API with Apache License 2.0 6 votes vote down vote up
@Test
public void testElements() {
    final LongStream stream = LongStream.of(-813, 123456, Integer.MAX_VALUE);
    final Long[] expected = new Long[] {-813L, 123456L, (long) Integer.MAX_VALUE};
    final Matcher<LongStream> matcher = elements(arrayContaining(expected));
    assertThat(stream, matcher);
    assertTrue(matcher.matches(stream));

    assertFalse(elements(arrayContaining(expected)).matches(LongStream.empty()));

    assertThat(matcher, description(allOf(
            containsString("LongStream elements"),
            containsString(Stream.of(expected)
                    .map(new Function<Long, String>() {
                        @Override
                        public String apply(Long t) {
                            return String.format("<%sL>", t.toString());
                        }
                    })
                    .collect(Collectors.joining(", ")))
    )));
}
 
Example #19
Source File: AddGroupDetailsViewModel.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
void create() {
  List<GroupMemberEntry.NewGroupCandidate> members     = Objects.requireNonNull(this.members.getValue());
  Set<RecipientId>                         memberIds   = Stream.of(members).map(member -> member.getMember().getId()).collect(Collectors.toSet());
  byte[]                                   avatarBytes = avatar.getValue();
  boolean                                  isGroupMms  = isMms.getValue() == Boolean.TRUE;
  String                                   groupName   = isGroupMms ? "" : name.getValue();

  if (!isGroupMms && TextUtils.isEmpty(groupName)) {
    groupCreateResult.postValue(GroupCreateResult.error(GroupCreateResult.Error.Type.ERROR_INVALID_NAME));
    return;
  }

  if (memberIds.isEmpty()) {
    groupCreateResult.postValue(GroupCreateResult.error(GroupCreateResult.Error.Type.ERROR_INVALID_MEMBER_COUNT));
    return;
  }

  repository.createPushGroup(memberIds,
                             avatarBytes,
                             groupName,
                             isGroupMms,
                             groupCreateResult::postValue);
}
 
Example #20
Source File: OfListTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamOfList() {
    final List<String> list = new ArrayList<String>(4);
    list.add("This");
    list.add(" is ");
    list.add("a");
    list.add(" test");

    String result = Stream.of(list)
            .collect(Collectors.joining());
    assertThat(result, is("This is a test"));
}
 
Example #21
Source File: OfCodePointTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringBuilder() {
    final String input = "test";

    final StringBuilder sb = new StringBuilder(input);
    String result = IntStream.ofCodePoints(sb)
            .mapToObj(new IntFunction<String>() {
                @Override
                public String apply(int i) {
                    return String.valueOf(Character.toChars(i));
                }
            }).collect(Collectors.joining());

    assertThat(input, is(result));
}
 
Example #22
Source File: OfMapTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamOfMap() {
    final Map<String, Integer> map = new HashMap<String, Integer>(4);
    map.put("This", 1);
    map.put(" is ", 2);
    map.put("a", 3);
    map.put(" test", 4);

    String result = Stream.of(map)
            .sortBy(Functions.<String, Integer>entryValue())
            .map(Functions.<String, Integer>entryKey())
            .collect(Collectors.joining());
    assertThat(result, is("This is a test"));
}
 
Example #23
Source File: OfListTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamOfList() {
    final List<String> list = new ArrayList<String>(4);
    list.add("This");
    list.add(" is ");
    list.add("a");
    list.add(" test");

    String result = Stream.of(list)
            .collect(Collectors.joining());
    assertThat(result, is("This is a test"));
}
 
Example #24
Source File: NotificationChannels.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(26)
@WorkerThread
public static synchronized void ensureCustomChannelConsistency(@NonNull Context context) {
  if (!supported()) {
    return;
  }
  Log.d(TAG, "ensureCustomChannelConsistency()");

  NotificationManager notificationManager = ServiceUtil.getNotificationManager(context);
  RecipientDatabase   db                  = DatabaseFactory.getRecipientDatabase(context);
  List<Recipient>     customRecipients    = new ArrayList<>();
  Set<String>         customChannelIds    = new HashSet<>();

  try (RecipientDatabase.RecipientReader reader = db.getRecipientsWithNotificationChannels()) {
    Recipient recipient;
    while ((recipient = reader.getNext()) != null) {
      customRecipients.add(recipient);
      customChannelIds.add(recipient.getNotificationChannel());
    }
  }

  Set<String> existingChannelIds  = Stream.of(notificationManager.getNotificationChannels()).map(NotificationChannel::getId).collect(Collectors.toSet());

  for (NotificationChannel existingChannel : notificationManager.getNotificationChannels()) {
    if (existingChannel.getId().startsWith(CONTACT_PREFIX) && !customChannelIds.contains(existingChannel.getId())) {
      Log.i(TAG, "Consistency: Deleting channel '"+ existingChannel.getId() + "' because the DB has no record of it.");
      notificationManager.deleteNotificationChannel(existingChannel.getId());
    } else if (existingChannel.getId().startsWith(MESSAGES_PREFIX) && !existingChannel.getId().equals(getMessagesChannel(context))) {
      Log.i(TAG, "Consistency: Deleting channel '"+ existingChannel.getId() + "' because it's out of date.");
      notificationManager.deleteNotificationChannel(existingChannel.getId());
    }
  }

  for (Recipient customRecipient : customRecipients) {
    if (!existingChannelIds.contains(customRecipient.getNotificationChannel())) {
      Log.i(TAG, "Consistency: Removing custom channel '"+ customRecipient.getNotificationChannel() + "' because the system doesn't have it.");
      db.setNotificationChannel(customRecipient.getId(), null);
    }
  }
}
 
Example #25
Source File: IpcamActivity.java    From openwebnet-android with MIT License 5 votes vote down vote up
private void initSpinnerStreamType() {
    List<IpcamModel.StreamType> streamTypes = IpcamModel.StreamType.toList();
    streamTypeArray = initSparseArray(streamTypes);

    List<String> streamTypeValues = Stream.of(streamTypes)
        .map(streamType -> getString(streamType.getLabelId())).collect(Collectors.toList());
    initSpinnerAdapter(spinnerIpcamStreamType, streamTypeValues);
}
 
Example #26
Source File: QMUserMemoryCache.java    From q-municate-android with Apache License 2.0 5 votes vote down vote up
@Override
public List<QMUser> getAllSorted(String sortedColumn, boolean ascending) {
    List<QMUser> result = null;
    result = Stream.of(usersMap.values()).sorted(new Comparator<QMUser>() {
        @Override
        public int compare(QMUser o1, QMUser o2) {
            return 0;
        }
    }).collect(Collectors.<QMUser>toList());

    return result;
}
 
Example #27
Source File: OfMapTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testStreamOfMap() {
    final Map<String, Integer> map = new HashMap<String, Integer>(4);
    map.put("This", 1);
    map.put(" is ", 2);
    map.put("a", 3);
    map.put(" test", 4);

    String result = Stream.of(map)
            .sortBy(Functions.<String, Integer>entryValue())
            .map(Functions.<String, Integer>entryKey())
            .collect(Collectors.joining());
    assertThat(result, is("This is a test"));
}
 
Example #28
Source File: OfCodePointTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testStringBuilder() {
    final String input = "test";

    final StringBuilder sb = new StringBuilder(input);
    String result = IntStream.ofCodePoints(sb)
            .mapToObj(new IntFunction<String>() {
                @Override
                public String apply(int i) {
                    return String.valueOf(Character.toChars(i));
                }
            }).collect(Collectors.joining());

    assertThat(input, is(result));
}
 
Example #29
Source File: DeviceServiceImpl.java    From openwebnet-android with MIT License 5 votes vote down vote up
@Override
public Observable<DeviceModel> sendRequest(DeviceModel device) {
    device.setInstantRequestDebug(Instant.now());

    return commonService.findClient(device.getGatewayUuid())
        .send(() -> device.getRequest())
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .map(openSession -> Joiner.on("")
            .join(Stream.of(openSession.getResponse())
                .map(response -> response.getValue())
                .collect(Collectors.toList())))
        .map(response -> {
            device.setInstantResponseDebug(Instant.now());
            device.setResponseDebug(response);

            boolean isExpectedResponse = device.getResponse().equals(response);
            device.setStatus(isExpectedResponse ? SUCCESS: FAIL);
            log.debug("SEND_REQUEST: [isExpected={}][response={}][value={}]",
                isExpectedResponse, device.getResponse(), response);
            return device;
        })
        .onErrorReturn(throwable -> {
            log.error("fail to send request for device={}", device.getUuid());
            device.setStatus(null);
            return device;
        });
}
 
Example #30
Source File: OfCodePointTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@Test
public void testSequenceHavingFourBytesEmoji() {
    String input = "This is a emoji \uD83D\uDCA9!";

    String result = IntStream.ofCodePoints(input)
            .mapToObj(new IntFunction<String>() {
                @Override
                public String apply(int i) {
                    return String.valueOf(Character.toChars(i));
                }
            }).collect(Collectors.joining());

    assertThat(input, is(result));
}