コード例 #1
0
ファイル: CollectionUtils.java プロジェクト: kohsuke/gradle
 public static <R, I, C extends Collection<R>> C collect(
     Iterable<? extends I> source, C destination, Transformer<R, I> transformer) {
   for (I item : source) {
     destination.add(transformer.transform(item));
   }
   return destination;
 }
コード例 #2
0
 /** @return the sum of the values of all the counters. */
 public final C sum() {
   final C sum = factory.newInstance();
   for (C c : counts.values()) {
     sum.add(c);
   }
   return sum;
 }
コード例 #3
0
ファイル: TreeUtils.java プロジェクト: rench/tx-parent
  /**
   * 根据指定集合生成树<br>
   * 首先找到不存在父节点的所有节点,将这些节点当作根节点<br>
   * 然后利用这些根节点迭代生成树<br>
   * 允许通过参数限制生成树的层数 <功能详细描述>
   *
   * @param treeAbleCollection
   * @param maxLevelIndex
   * @return [参数说明]
   * @return C [返回类型说明]
   * @exception throws [异常类型] [异常说明]
   * @see [类、类#方法、类#成员]
   */
  @SuppressWarnings("rawtypes")
  public static <C extends Collection<T>, T extends TreeAble> C changToTree(
      C treeAbleCollection, int maxLevelIndex) {
    // 判断入参是否合法
    if (treeAbleCollection == null || treeAbleCollection.size() == 0) {
      // 如果root或需要转换的集合其中有一个为空,直接返回root集合当作结果
      return treeAbleCollection;
    }

    C parentNodeCollection = newCollectionInstance(treeAbleCollection);

    // 循环得到当前传入list上级节点有多少个
    // 并进行非法节点过滤,如果某节点id  = parentId将会造成死循环 ,将这样的节点抛弃
    Map<String, C> parentIdIndexMap = new HashMap<String, C>();
    Set<String> treeAbleNodeIdSet = new HashSet<String>();
    for (T treeAbleTemp : treeAbleCollection) {
      String superId = treeAbleTemp.getParentId();
      String id = treeAbleTemp.getId();

      treeAbleNodeIdSet.add(treeAbleTemp.getId());
      if (StringUtils.isEmpty(id) || id.equals(superId)) {
        // 并进行非法节点过滤,如果某节点id  = parentId将会造成死循环
        // 非法节点在该方法中将被当作根节点放置于树中
        // doNothing
        parentNodeCollection.add(treeAbleTemp);
        continue;
      }

      // 根据父节点形成父ID与集合的映射
      if (parentIdIndexMap.containsKey(superId)) {
        parentIdIndexMap.get(superId).add(treeAbleTemp);
      } else {
        C collectionTemp = newCollectionInstance(treeAbleCollection);
        collectionTemp.add(treeAbleTemp);
        parentIdIndexMap.put(superId, collectionTemp);
      }
    }

    // 迭代生成根节点集合

    for (T treeAbleTemp : treeAbleCollection) {
      if (!treeAbleNodeIdSet.contains(treeAbleTemp.getParentId())) {
        parentNodeCollection.add(treeAbleTemp);
      }
    }
    return changeToTreeByParentIdIndexMap(parentNodeCollection, maxLevelIndex, parentIdIndexMap);
  }
コード例 #4
0
  public static <K, V, C extends Collection<K>> C toCollection(
      final C target, final V[] collection, final ITranslator<V, K> translator) {
    for (final V value : collection) {
      target.add(translator.translate(value));
    }

    return target;
  }
コード例 #5
0
  public static <T, C extends Collection<T>> C addAll(
      C collection, Iterable<? extends T> iterable) {
    for (T item : iterable) {
      collection.add(item);
    }

    return collection;
  }
コード例 #6
0
 @NotNull
 private static <T, C extends Collection<T>> C copy(
     @NotNull C collection, @NotNull Iterable<? extends T> elements) {
   for (T element : elements) {
     collection.add(element);
   }
   return collection;
 }
コード例 #7
0
ファイル: Maps.java プロジェクト: automenta/corenlp
 /**
  * Adds the value to the collection given by map.get(key). A new collection is created using the
  * supplied CollectionFactory.
  */
 public static <K, V, C extends Collection<V>> void putIntoValueCollection(
     Map<K, C> map, K key, V value, CollectionFactory<V> cf) {
   C c = map.get(key);
   if (c == null) {
     c = ErasureUtils.<C>uncheckedCast(cf.newCollection());
     map.put(key, c);
   }
   c.add(value);
 }
コード例 #8
0
 private C collectionFromWire() {
   C c = factory.get();
   @SuppressWarnings("ConstantConditions")
   final ValueIn valueIn = ((Wire) outWire).getValueIn();
   while (valueIn.hasNextSequenceItem()) {
     c.add(fromWire.apply(valueIn));
   }
   return c;
 }
コード例 #9
0
 public static <T, C extends Collection<T>> C filter(
     Iterable<? extends T> source, C destination, Spec<? super T> filter) {
   for (T item : source) {
     if (filter.isSatisfiedBy(item)) {
       destination.add(item);
     }
   }
   return destination;
 }
コード例 #10
0
 /**
  * Removes at most n elements from the given iterable, and adds it to the output collection
  *
  * @param <T>
  * @param <C>
  * @param iterable
  * @param amountOfElements the max amount of elements to select from the iterable. Must be >= 0
  * @param collection
  * @return the output collection
  */
 @NonNull
 public static <T, C extends Collection<T>> C move(
     @NonNull Iterable<T> iterable, @NotNegative int amountOfElements, @NonNull C collection) {
   Iterator<? extends T> iter = iterable.iterator();
   for (int i = 0; i < amountOfElements && iter.hasNext(); i++) {
     collection.add(iter.next());
     iter.remove();
   }
   return collection;
 }
コード例 #11
0
ファイル: ObjectConnection.java プロジェクト: redfagus/anno4j
 private <C extends Collection<URI>> C addConcept(Resource resource, Class<?> role, C set)
     throws RepositoryException {
   URI type = of.getNameOf(role);
   if (type == null) {
     throw new ObjectPersistException(
         "Concept is anonymous or is not registered: " + role.getSimpleName());
   }
   types.addTypeStatement(resource, type);
   set.add(type);
   return set;
 }
コード例 #12
0
 /**
  * Removes all elements from the given iterable that evalute to true, and adds them to the given
  * collection
  *
  * @param iterable
  * @param collection
  * @param predicate
  * @param <T>
  * @param <C>
  * @return the given collection
  */
 @NonNull
 public static <T, C extends Collection<T>> C move(
     @NonNull Iterable<T> iterable, @NonNull C collection, @NonNull Evaluable<T> predicate) {
   for (Iterator<T> iter = iterable.iterator(); iter.hasNext(); ) {
     T element = iter.next();
     if (predicate.eval(element)) {
       iter.remove();
       collection.add(element);
     }
   }
   return collection;
 }
コード例 #13
0
 private <C extends Collection<E>, E> C _convertContents(
     Collection collection, Class<C> collectionClass, Class<E> elementClass) {
   C coll = (C) CollectionUtils.instanceOf(collectionClass);
   for (Object obj : collection) {
     try {
       E e = convert(obj, elementClass);
       coll.add(e);
     } catch (ConversionException ex) {
     }
   }
   setCachedElementType(coll, elementClass);
   return coll;
 }
コード例 #14
0
 /** Given a map that maps to collections, adds a new key/value pair or introduces the key */
 @SuppressWarnings("unchecked")
 public static <K, V, C extends Collection<V>, L extends Collection> void addKeyValue(
     Map<K, C> map, K key, V value, Class<L> collectionType) {
   C coll = map.get(key);
   if (coll == null) {
     try {
       map.put(key, coll = (C) collectionType.newInstance());
     } catch (Exception e) {
       throw new RuntimeException(e);
     }
   }
   coll.add(value);
 }
コード例 #15
0
ファイル: JoinRowMapper.java プロジェクト: Tob1112/seungbeomi
 private <C extends Collection<R>> C mapInto(C collection, ResultSet rs) throws SQLException {
   R root = null;
   I previousId = null;
   while (rs.next()) {
     I id = mapId(rs);
     if (!id.equals(previousId)) {
       root = mapRoot(id, rs);
       collection.add(root);
     }
     addChild(root, rs);
     previousId = id;
   }
   return collection;
 }
コード例 #16
0
 @Override
 protected C readValue(Command resp) throws TraCIException {
   Storage content = resp.content();
   List<String> ids = new StringList(content, true);
   C out = makeCollection();
   for (String id : ids) {
     try {
       out.add(repository.getByID(id));
     } catch (IOException e) {
       throw new TraCIException(e.toString());
     }
   }
   return out;
 }
コード例 #17
0
  @Override
  public <E, C extends Collection<? super E>> C readCollection(
      String fieldName, C collection, Class<E> elementClass) throws IOException {
    final FieldDescriptor fd = messageContext.marshallerDelegate.getFieldByName(fieldName);
    checkFieldRead(fd, true);

    if (primitiveTypes.contains(fd.getType())) {
      readPrimitiveCollection(fd, (Collection<Object>) collection, elementClass);
      return collection;
    }

    // todo validate type is compatible with readCollection
    final int expectedTag = WireFormat.makeTag(fd.getNumber(), fd.getType().getWireType());

    while (true) {
      Object o = messageContext.unknownFieldSet.consumeTag(expectedTag);
      if (o == null) {
        break;
      }
      byte[] byteArray = (byte[]) o;
      RawProtoStreamReader in = RawProtoStreamReaderImpl.newInstance(byteArray);
      collection.add(readNestedObject(fd, elementClass, in, byteArray.length));
    }

    while (true) {
      int tag = messageContext.in.readTag();
      if (tag == 0) {
        break;
      }
      if (tag == expectedTag) {
        collection.add(readNestedObject(fd, elementClass, messageContext.in, -1));
      } else {
        messageContext.unknownFieldSet.readSingleField(tag, messageContext.in);
      }
    }
    return collection;
  }
コード例 #18
0
ファイル: ObjectConnection.java プロジェクト: redfagus/anno4j
 private <C extends Collection<URI>> C getTypes(Class<?> role, C set) throws RepositoryException {
   URI type = of.getNameOf(role);
   if (type == null) {
     Class<?> superclass = role.getSuperclass();
     if (superclass != null) {
       getTypes(superclass, set);
     }
     Class<?>[] interfaces = role.getInterfaces();
     for (int i = 0, n = interfaces.length; i < n; i++) {
       getTypes(interfaces[i], set);
     }
   } else {
     set.add(type);
   }
   return set;
 }
コード例 #19
0
ファイル: Lang.java プロジェクト: flymichael/nutz
 /**
  * 将一个或者多个数组填入一个集合。
  *
  * @param <C> 集合类型
  * @param <T> 数组元素类型
  * @param coll 集合
  * @param objss 数组 (数目可变)
  * @return 集合对象
  */
 public static <C extends Collection<T>, T> C fill(C coll, T[]... objss) {
   for (T[] objs : objss) for (T obj : objs) coll.add(obj);
   return coll;
 }
コード例 #20
0
 /** {@inheritDoc} */
 @Override
 public boolean add(final N e) {
   return collection.add(funcNtoM.apply(e));
 }
コード例 #21
0
  /**
   * Convert an Object to a Collection with elements of the desired type. If it is a Collection and
   * it is of the same collection and element type it is returned as is, otherwise a new Collection
   * is created with all elements converted to the desired type. If it is a String representation of
   * a Collection it is converted to a Collection.
   *
   * @param <E> The element type.
   * @param <C> The Collection type.
   * @param obj The Object to be converted.
   * @param collectionType The desired Collection type.
   * @param elementType The desired element type.
   * @param emptyIfNull Whether or not an empty Collection should be returned if the Collection
   *     could not be converted.
   * @return The converted Collection.
   */
  public <E, C extends Collection<E>> C convertToCollection(
      Object obj, Class<C> collectionType, Class<E> elementType, boolean emptyIfNull) {
    // Grab defaults for types if interfaces or non-datareference collections are provided
    Class<? extends C> constructionCollectionType;
    Class<? extends E> constructionElementType;
    if (collectionType.equals(List.class)) {
      if (DataReferencable.class.isAssignableFrom(elementType)) {
        constructionCollectionType = (Class) DataReferenceList.class;
        constructionElementType = (Class) DataReference.class;
      } else {
        constructionCollectionType = (Class) ArrayList.class;
      }
    } else if (collectionType.equals(Set.class)) {
      if (DataReferencable.class.isAssignableFrom(elementType)) {
        constructionElementType = (Class) DataReference.class;
        throw new IllegalArgumentException(
            "Set class is not supported for DataReferencable elements");
      }
      constructionCollectionType = (Class) HashSet.class;
    } else {
      constructionCollectionType = collectionType;
    }

    if (obj != null) {
      if (obj instanceof Collection) {
        // If it's already a collection
        Collection collection = (Collection) obj;
        Class cachedElementType = getCachedElementType(collection);
        // If we have cached it's element type return if same
        if (cachedElementType != null
            && elementType.isAssignableFrom(cachedElementType)
            && collection.getClass().equals(constructionCollectionType)) {
          setCachedElementType(collection, elementType);
          return (C) collection;
        } else {
          return _convertContents(collection, constructionCollectionType, elementType);
        }
      } else {
        try {
          // If it's a single value convertable to E
          E e = convert(obj, elementType);
          C c = CollectionUtils.instanceOf(constructionCollectionType);
          c.add(e);
          return c;
        } catch (ConversionException ex) {
        }
        try {
          // If it's a string representation of one or many E's
          String string = convert(obj, String.class);
          String[] split = TextUtils.splitOnSpacesAndCommas(string);
          C c = CollectionUtils.instanceOf(constructionCollectionType);
          for (String str : split) {
            try {
              E e = convert(obj, elementType);
              c.add(e);
            } catch (ConversionException ex) {

            }
          }
          if (!c.isEmpty()) {
            return c;
          }
        } catch (ConversionException ex) {

        }
      }
    }

    // Fall through to here if a collection could not be converted for any reason
    if (emptyIfNull) {
      return CollectionUtils.instanceOf(constructionCollectionType);
    } else {
      return null;
    }
  }
コード例 #22
0
        @Override
        public void readMarshallable(WireIn wire) throws IllegalStateException {
          @SuppressWarnings("ConstantConditions")
          final Bytes<?> outBytes = outWire.bytes();

          try {

            final StringBuilder eventName = Wires.acquireStringBuilder();
            @SuppressWarnings("ConstantConditions")
            final ValueIn valueIn = inWire.readEventName(eventName);

            outWire.writeDocument(
                true, w -> w.writeEventName(CoreFields.tid).int64(CollectionWireHandler.this.tid));

            outWire.writeDocument(
                false,
                out -> {

                  // note :  remove on the key-set returns a boolean and on the map returns the
                  // old value
                  if (EventId.remove.contentEquals(eventName)) {
                    outWire
                        .write(CoreFields.reply)
                        .bool(underlyingCollection.remove(fromWire.apply(valueIn)));
                    return;
                  }

                  // note :  remove on the key-set returns a boolean and on the map returns the
                  // old value
                  if (EventId.iterator.contentEquals(eventName)) {
                    final ValueOut valueOut = out.writeEventName(CoreFields.reply);
                    valueOut.sequence(v -> underlyingCollection.forEach(e -> toWire.accept(v, e)));
                    return;
                  }

                  if (EventId.numberOfSegments.contentEquals(eventName)) {
                    outWire.write(CoreFields.reply).int32(1);
                    return;
                  }

                  if (EventId.isEmpty.contentEquals(eventName)) {
                    outWire.write(CoreFields.reply).bool(underlyingCollection.isEmpty());
                    return;
                  }

                  if (EventId.size.contentEquals(eventName)) {
                    outWire.write(CoreFields.reply).int32(underlyingCollection.size());
                    return;
                  }

                  if (EventId.clear.contentEquals(eventName)) {
                    underlyingCollection.clear();
                    return;
                  }

                  if (EventId.contains.contentEquals(eventName)) {
                    outWire
                        .write(CoreFields.reply)
                        .bool(underlyingCollection.contains(fromWire.apply(valueIn)));
                    return;
                  }

                  if (EventId.add.contentEquals(eventName)) {
                    outWire
                        .write(CoreFields.reply)
                        .bool(underlyingCollection.add(fromWire.apply(valueIn)));
                    return;
                  }

                  if (EventId.remove.contentEquals(eventName)) {
                    outWire
                        .write(CoreFields.reply)
                        .bool(underlyingCollection.remove(fromWire.apply(valueIn)));
                    return;
                  }

                  if (EventId.containsAll.contentEquals(eventName)) {
                    outWire
                        .write(CoreFields.reply)
                        .bool(underlyingCollection.remove(collectionFromWire()));
                    return;
                  }

                  if (EventId.addAll.contentEquals(eventName)) {
                    outWire
                        .write(CoreFields.reply)
                        .bool(underlyingCollection.addAll(collectionFromWire()));
                    return;
                  }

                  if (EventId.removeAll.contentEquals(eventName)) {
                    outWire
                        .write(CoreFields.reply)
                        .bool(underlyingCollection.removeAll(collectionFromWire()));
                    return;
                  }

                  if (EventId.retainAll.contentEquals(eventName)) {
                    outWire
                        .write(CoreFields.reply)
                        .bool(underlyingCollection.retainAll(collectionFromWire()));
                    return;
                  }

                  throw new IllegalStateException("unsupported event=" + eventName);
                });
          } catch (Exception e) {
            LOG.error("", e);
          } finally {

            if (YamlLogging.showServerWrites) {
              long len = outBytes.writePosition();
              if (len >= SIZE_OF_SIZE) {
                String s = Wires.fromSizePrefixedBlobs(outBytes);

                LOG.info("server writes:\n\n" + s);
              }
            }
          }
        }
コード例 #23
0
ファイル: Miscellaneous.java プロジェクト: fedorov-s-n/JUnix
 public CollectionBuilder<E, C> add(E e) {
   c.add(e);
   return this;
 }