Java Code Examples for java.util.Collection#clear()

The following examples show how to use java.util.Collection#clear() . 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: FilteredEntryMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
boolean removeEntriesIf(Predicate<? super Entry<K, Collection<V>>> predicate) {
  Iterator<Entry<K, Collection<V>>> entryIterator = unfiltered.asMap().entrySet().iterator();
  boolean changed = false;
  while (entryIterator.hasNext()) {
    Entry<K, Collection<V>> entry = entryIterator.next();
    K key = entry.getKey();
    Collection<V> collection = filterCollection(entry.getValue(), new ValuePredicate(key));
    if (!collection.isEmpty()
        && predicate.apply(Maps.immutableEntry(key, collection))) {
      if (collection.size() == entry.getValue().size()) {
        entryIterator.remove();
      } else {
        collection.clear();
      }
      changed = true;
    }
  }
  return changed;
}
 
Example 2
Source File: ListTypeTreeNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void updateValueFromChildren(TypeNodeData inData) {
    /**
     * create a new ArrayList from all of the child values.
     */
    TypeNodeData data = (TypeNodeData)this.getUserObject();
    
    Collection c = (Collection)data.getTypeValue();
    if (c == null) return;
    
    c.clear();
    for(int ii=0; ii < this.getChildCount(); ii++) {
        DefaultMutableTreeNode childNode = (DefaultMutableTreeNode)this.getChildAt(ii);
        TypeNodeData childData = (TypeNodeData)childNode.getUserObject();
        if(null != childData.getTypeValue()) {
            c.add(childData.getTypeValue());
        }
    }
    
    DefaultMutableTreeNode parentNode = (DefaultMutableTreeNode) this.getParent();
    if (parentNode != null && parentNode instanceof ParameterTreeNode) {
        ((ParameterTreeNode)parentNode).updateValueFromChildren(data);
    }
}
 
Example 3
Source File: GridCacheSetImpl.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void clear() {
    try {
        onAccess();

        try (GridCloseableIterator<T> iter = iterator0()) {
            Collection<SetItemKey> rmvKeys = new ArrayList<>(BATCH_SIZE);

            for (T val : iter) {
                rmvKeys.add(itemKey(val));

                if (rmvKeys.size() == BATCH_SIZE) {
                    retryRemoveAll(rmvKeys);

                    rmvKeys.clear();
                }
            }

            if (!rmvKeys.isEmpty())
                retryRemoveAll(rmvKeys);
        }
    }
    catch (IgniteCheckedException e) {
        throw U.convertException(e);
    }
}
 
Example 4
Source File: RansacRegressionFilter.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void filter( List< PointMatch > candidates, Collection< PointMatch > inliers )
{
	try
	{
		if (
			!model.filterRansac(
					candidates,
					inliers,
					iterations,
					maxEpsilon,
					minInlierRatio,
					minNumInliers,
					maxTrust ) )
			inliers.clear();
	}
	catch ( Exception e )
	{
		inliers.clear();
	}
}
 
Example 5
Source File: ObjectUtilities.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns a new collection containing clones of all the items in the
 * specified collection.
 *
 * @param collection the collection (<code>null</code> not permitted).
 * @return A new collection containing clones of all the items in the
 *         specified collection.
 * @throws CloneNotSupportedException if any of the items in the collection
 *                                    cannot be cloned.
 */
public static Collection deepClone(final Collection collection)
    throws CloneNotSupportedException {

    if (collection == null) {
        throw new IllegalArgumentException("Null 'collection' argument.");
    }
    // all JDK-Collections are cloneable ...
    // and if the collection is not clonable, then we should throw
    // a CloneNotSupportedException anyway ...
    final Collection result
        = (Collection) ObjectUtilities.clone(collection);
    result.clear();
    final Iterator iterator = collection.iterator();
    while (iterator.hasNext()) {
        final Object item = iterator.next();
        if (item != null) {
            result.add(clone(item));
        }
        else {
            result.add(null);
        }
    }
    return result;
}
 
Example 6
Source File: ComputeResourceService.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private <T> Map<FutureResult, List<T>> waitForRequests(Collection<Future<ResourceRequestResult<T>>> futures) {
    Map<FutureResult, List<T>> result = new EnumMap<>(FutureResult.class);
    result.put(FutureResult.FAILED, new ArrayList<>());
    result.put(FutureResult.SUCCESS, new ArrayList<>());
    int requests = futures.size();
    LOGGER.debug("Waiting for {} requests to finish", requests);
    try {
        for (Future<ResourceRequestResult<T>> future : futures) {
            ResourceRequestResult<T> resourceRequestResult = future.get();
            if (FutureResult.FAILED == resourceRequestResult.getStatus()) {
                result.get(FutureResult.FAILED).add(resourceRequestResult.getResult());
            } else {
                result.get(FutureResult.SUCCESS).add(resourceRequestResult.getResult());
            }
        }
    } catch (InterruptedException | ExecutionException e) {
        LOGGER.error("Failed to execute the request", e);
    }
    LOGGER.debug("{} requests have finished, continue with next group", requests);
    futures.clear();
    return result;
}
 
Example 7
Source File: AbstractMapBasedMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public Iterator<K> iterator() {
  final Iterator<Map.Entry<K, Collection<V>>> entryIterator = map().entrySet().iterator();
  return new Iterator<K>() {
    Map.Entry<K, Collection<V>> entry;

    @Override
    public boolean hasNext() {
      return entryIterator.hasNext();
    }

    @Override
    public K next() {
      entry = entryIterator.next();
      return entry.getKey();
    }

    @Override
    public void remove() {
      checkRemove(entry != null);
      Collection<V> collection = entry.getValue();
      entryIterator.remove();
      totalSize -= collection.size();
      collection.clear();
    }
  };
}
 
Example 8
Source File: TextDiff.java    From pumpernickel with MIT License 5 votes vote down vote up
/**
 * This chooses to record the results in the collection provided or discard
 * it.
 * <p>
 * If includeAllSolutions is true, then this solution is always recorded.
 * Otherwise this solution is only recorded if the complexity is the lowest
 * complexity yet detected.
 * 
 * @param results
 *            the collection to store the solution in if this method decides
 *            to keep it.
 * @param solution
 *            the new solution to process.
 * @param key
 *            the key describing the query being made.
 */
protected void processSolution(Collection<DiffSegment> results,
		DiffSegment solution, Key key, Complexity minComplexity) {
	boolean isValid = true;
	DiffSegment tail = solution.getTail();
	if (tail instanceof SplitSegment) {
		SplitSegment tailSplit = (SplitSegment) tail;

		if (tailSplit.textA.length() > 0 && tailSplit.textB.length() > 0) {
			char chA = tailSplit.textA.charAt(tailSplit.textA.length() - 1);
			char chB = tailSplit.textB.charAt(tailSplit.textB.length() - 1);
			if (chA == chB) {
				isValid = false;
			}
		}
	}
	if (!isValid)
		return;

	int complexity = solution.getComplexity();
	if (key.includeAllSolutions) {
		results.add(solution);
	} else {
		if ((!key.includeAllSolutions) && complexity < minComplexity.value) {
			results.clear();
			minComplexity.value = complexity;
		}
		if (complexity == minComplexity.value) {
			results.add(solution);
		}
	}
}
 
Example 9
Source File: IndexFieldDataService.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public synchronized void clear() {
    parentIndexFieldData = null;
    List<Throwable> exceptions = new ArrayList<>(0);
    final Collection<IndexFieldDataCache> fieldDataCacheValues = fieldDataCaches.values();
    for (IndexFieldDataCache cache : fieldDataCacheValues) {
        try {
            cache.clear();
        } catch (Throwable t) {
            exceptions.add(t);
        }
    }
    fieldDataCacheValues.clear();
    ExceptionsHelper.maybeThrowRuntimeAndSuppress(exceptions);
}
 
Example 10
Source File: AbstractMapBasedMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public Collection<V> remove(Object key) {
  Collection<V> collection = submap.remove(key);
  if (collection == null) {
    return null;
  }
  Collection<V> output = createCollection();
  output.addAll(collection);
  totalSize -= collection.size();
  collection.clear();
  return output;
}
 
Example 11
Source File: FieldListAxisDescription.java    From chart-fx with Apache License 2.0 5 votes vote down vote up
protected final void execFieldReader(final Object obj, ClassFieldDescription field) throws IllegalAccessException {
    Collection<AxisDescription> setVal = (Collection<AxisDescription>) field.getField().get(obj); // NOPMD
    // N.B. cast should fail at runtime (points to lib inconsistency)
    setVal.clear();
    final int nElements = ioBuffer.getInt(); // number of elements
    for (int i = 0; i < nElements; i++) {
        // read start marker
        BinarySerialiser.getFieldHeader(ioBuffer);
        final byte startMarker = ioBuffer.getByte();
        if (startMarker != DataType.START_MARKER.getAsByte()) {
            throw new IllegalStateException("corrupt start marker, value is " + startMarker + " vs. should "
                                            + DataType.START_MARKER.getAsByte());
        }

        BinarySerialiser.getFieldHeader(ioBuffer);
        String axisName = ioBuffer.getString();
        BinarySerialiser.getFieldHeader(ioBuffer);
        String axisUnit = ioBuffer.getString();
        BinarySerialiser.getFieldHeader(ioBuffer);
        double min = ioBuffer.getDouble();
        BinarySerialiser.getFieldHeader(ioBuffer);
        double max = ioBuffer.getDouble();

        DefaultAxisDescription ad = new DefaultAxisDescription(null, axisName, axisUnit, min, max); // NOPMD
        // N.B. PMD - unavoidable in-loop instantiation

        BinarySerialiser.getFieldHeader(ioBuffer);
        final byte endMarker = ioBuffer.getByte();
        if (endMarker != DataType.END_MARKER.getAsByte()) {
            throw new IllegalStateException(
                    "corrupt end marker, value is " + endMarker + " vs. should " + DataType.END_MARKER.getAsByte());
        }

        setVal.add(ad);
    }

    field.getField().set(obj, setVal);
}
 
Example 12
Source File: AbstractMapBasedMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Removes all values for the provided key.
 */

private void removeValuesForKey(Object key) {
  Collection<V> collection = Maps.safeRemove(map, key);
  if (collection != null) {
    int count = collection.size();
    collection.clear();
    totalSize -= count;
  }
        }
 
Example 13
Source File: AbstractMapBasedMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void clear() {
  // Clear each collection, to make previously returned collections empty.
  for (Collection<V> collection : map.values()) {
    collection.clear();
  }
  map.clear();
  totalSize = 0;
}
 
Example 14
Source File: EnrolmentCertificate.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
final private String getEnrolmentsInfo() {
    final StringBuilder result = new StringBuilder();
    final EnrolmentCertificateRequest request = getDocumentRequest();

    if (request.getDetailed()) {
        final Collection<IEnrolment> enrolments =
                new TreeSet<>(Enrolment.COMPARATOR_BY_EXECUTION_YEAR_AND_NAME_AND_ID);

        enrolments.addAll(request.getEntriesToReport());
        reportEnrolments(result, enrolments);
        enrolments.clear();

        enrolments.addAll(request.getExtraCurricularEntriesToReport());
        if (!enrolments.isEmpty()) {
            reportRemainingEnrolments(result, enrolments, "Extra-Curriculares");
        }
        enrolments.clear();

        enrolments.addAll(request.getPropaedeuticEntriesToReport());
        if (!enrolments.isEmpty()) {
            reportRemainingEnrolments(result, enrolments, "Propedeuticas");
        }
        enrolments.clear();

        enrolments.addAll(request.getExternalEnrolments());
        if (!enrolments.isEmpty()) {
            reportRemainingEnrolments(result, enrolments, "Externas");
        }

        result.append(generateEndLine());
    }

    return result.toString();
}
 
Example 15
Source File: AbstractMapBasedMultimap.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
* {@inheritDoc}
*
* <p>The returned collection is immutable.
*/

     @Override
     public Collection<V> removeAll(@Nullable Object key) {
 Collection<V> collection = map.remove(key);
 if (collection == null) {
         return createUnmodifiableEmptyCollection();
 }
 Collection<V> output = createCollection();
 output.addAll(collection);
 totalSize -= collection.size();
 collection.clear();
 return unmodifiableCollectionSubclass(output);
     }
 
Example 16
Source File: MemoryManager.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
/**
 * Tries to release many memory segments together.
 *
 * <p>If the memory manager manages pre-allocated memory, the memory segment goes back to the memory pool.
 * Otherwise, the segment is only freed and made eligible for reclamation by the GC.
 *
 * @param segments The segments to be released.
 * @throws NullPointerException Thrown, if the given collection is null.
 * @throws IllegalArgumentException Thrown, id the segments are of an incompatible type.
 */
public void release(Collection<MemorySegment> segments) {
	if (segments == null) {
		return;
	}

	// -------------------- BEGIN CRITICAL SECTION -------------------
	synchronized (lock) {
		if (isShutDown) {
			throw new IllegalStateException("Memory manager has been shut down.");
		}

		// since concurrent modifications to the collection
		// can disturb the release, we need to try potentially multiple times
		boolean successfullyReleased = false;
		do {
			final Iterator<MemorySegment> segmentsIterator = segments.iterator();

			Object lastOwner = null;
			Set<MemorySegment> segsForOwner = null;

			try {
				// go over all segments
				while (segmentsIterator.hasNext()) {

					final MemorySegment seg = segmentsIterator.next();
					if (seg == null || seg.isFreed()) {
						continue;
					}

					final Object owner = seg.getOwner();

					try {
						// get the list of segments by this owner only if it is a different owner than for
						// the previous one (or it is the first segment)
						if (lastOwner != owner) {
							lastOwner = owner;
							segsForOwner = this.allocatedSegments.get(owner);
						}

						// remove the segment from the list
						if (segsForOwner != null) {
							segsForOwner.remove(seg);
							if (segsForOwner.isEmpty()) {
								this.allocatedSegments.remove(owner);
							}
						}

						if (isPreAllocated) {
							memoryPool.returnSegmentToPool(seg);
						}
						else {
							seg.free();
							numNonAllocatedPages++;
						}
					}
					catch (Throwable t) {
						throw new RuntimeException(
								"Error removing book-keeping reference to allocated memory segment.", t);
					}
				}

				segments.clear();

				// the only way to exit the loop
				successfullyReleased = true;
			}
			catch (ConcurrentModificationException | NoSuchElementException e) {
				// this may happen in the case where an asynchronous
				// call releases the memory. fall through the loop and try again
			}
		} while (!successfullyReleased);
	}
	// -------------------- END CRITICAL SECTION -------------------
}
 
Example 17
Source File: GLUtils.java    From ehacks-pro with GNU General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public void removeDuplicated(Collection list) {
    HashSet set = new HashSet(list);
    list.clear();
    list.addAll(set);
}
 
Example 18
Source File: ServerUpdaterDelegateImpl.java    From Javacord with Apache License 2.0 4 votes vote down vote up
@Override
public void removeAllRolesFromUser(User user) {
    Collection<Role> userRoles = this.userRoles.computeIfAbsent(user, u -> new ArrayList<>(server.getRoles(u)));
    userRoles.clear();
}
 
Example 19
Source File: GraphTest.java    From quarks with Apache License 2.0 4 votes vote down vote up
@Test
public void testGraphAccess() {
    Graph g = getGraph();
    
    TestOp<String, Integer> op = new TestOp<>();

    Vertex<TestOp<String, Integer>, String, Integer> v = g.insert(op, 1, 1);
    assertNotNull(v);
    assertSame(op, v.getInstance());

    Collection<Vertex<? extends Oplet<?, ?>, ?, ?>> c = getGraph().getVertices();
    assertNotNull(c);

    assertFalse(c.isEmpty());
    assertEquals(1, c.size());

    assertSame(v, c.toArray()[0]);
    
    assertTrue(getGraph().getEdges().isEmpty());

    try {
        c.clear();
        fail("Was able to modify graph collection");
    } catch (UnsupportedOperationException e) {
        // ok - expected
    }
    
    
    TestOp<Integer, Void> op2 = new TestOp<>();
    Vertex<TestOp<Integer, Void>, Integer, Void> v2 = g.insert(op2, 1, 0);
    
    c = getGraph().getVertices();
    assertNotNull(c);

    assertFalse(c.isEmpty());
    assertEquals(2, c.size());

    assertSame(v, c.toArray()[0]);
    assertSame(v2, c.toArray()[1]);
    
    assertTrue(getGraph().getEdges().isEmpty());
    
    v.getConnectors().get(0).connect(v2, 0);
    
    Collection<Edge> edges = getGraph().getEdges();
    assertFalse(edges.isEmpty());
    assertEquals(1, edges.size());
    
    Edge vtov2 = (Edge) edges.toArray()[0];
    assertSame(v, vtov2.getSource());
    assertEquals(0, vtov2.getSourceOutputPort());
    
    assertSame(v2, vtov2.getTarget());
    assertEquals(0, vtov2.getTargetInputPort());
}
 
Example 20
Source File: TaskPlannerUtil.java    From AILibs with GNU Affero General Public License v3.0 4 votes vote down vote up
private void getOracleGroundings(final Collection<VariableParam> ungroundParamsInEvaluablePrecondition, final Queue<Literal> literalsOrderedByOracability, final Monom state, final Set<VariableParam> paramsGroundSoFar,
		final Collection<Map<VariableParam, ConstantParam>> groundingsFixedSoFar, final Map<VariableParam, ConstantParam> basicConstantGrounding) {
	if (literalsOrderedByOracability.isEmpty()) {
		return;
	}

	Literal l = literalsOrderedByOracability.poll();

	/* check whether the literal only needs to be queried for one param */
	Collection<LiteralParam> paramsThatNeedGrounding = SetUtil.intersection(SetUtil.difference(ungroundParamsInEvaluablePrecondition, paramsGroundSoFar), l.getParameters());
	logger.info("Now checking validity of {}. Set of params that still need grounding: {}", l, paramsThatNeedGrounding);
	if (paramsThatNeedGrounding.size() > 1) {
		throw new UnsupportedOperationException("Currently only support for at most one unground variable! Here, the following variables of \"" + l + "\"need grounding: " + paramsThatNeedGrounding);
	}

	/* now go over all previous groundings and check them */
	List<Map<VariableParam, ConstantParam>> localCopyOfCurrentGrounding = new ArrayList<>(groundingsFixedSoFar);
	VariableParam paramToBeGround = null;

	/* create an array with the parameters of the literal defined by the basic grounding, and determine the one to be oracled */
	ConstantParam[] params = new ConstantParam[l.getParameters().size()];
	int indexOfParam = -1;
	Map<VariableParam, Integer> positionsOfVariableParams = new HashMap<>();
	for (int i = 0; i < params.length; i++) {
		LiteralParam param = l.getParameters().get(i);
		boolean parameterIsConstant = param instanceof ConstantParam;
		boolean parameterIsGround = basicConstantGrounding.containsKey(param);
		boolean parameterHasBeenDecidedByOracle = !(parameterIsConstant || parameterIsGround) && paramsGroundSoFar.contains(param);
		if (parameterIsConstant) {
			params[i] = (ConstantParam) param;
		} else if (parameterIsGround) {
			params[i] = basicConstantGrounding.get(param);
		} else {
			positionsOfVariableParams.put((VariableParam) param, i);
			if (!parameterHasBeenDecidedByOracle) {
				indexOfParam = i;
				paramToBeGround = (VariableParam) l.getParameters().get(i);
			}
		}
	}

	/* update list of solutions */
	groundingsFixedSoFar.clear();
	for (Map<VariableParam, ConstantParam> previouslyOracledGrounding : localCopyOfCurrentGrounding) {

		logger.info("Considering combination of previously fixed oracle decisions: {}", previouslyOracledGrounding);

		/* completing the param array */
		for (VariableParam oracledParam : paramsGroundSoFar) {
			if (!positionsOfVariableParams.containsKey(oracledParam)) {
				logger.debug("Ignoring ground value {} of param {}, because this param does not occur in the literal", previouslyOracledGrounding.get(oracledParam), oracledParam);
				continue;
			}
			logger.debug("Inserting {} at position {} in the param array.", previouslyOracledGrounding.get(oracledParam), positionsOfVariableParams.get(oracledParam));
			params[positionsOfVariableParams.get(oracledParam)] = previouslyOracledGrounding.get(oracledParam);
		}
		if (logger.isInfoEnabled()) {
			logger.info("Params for literal are {}", Arrays.toString(params));
		}

		/* recover the parameter to ground */
		final int finalizedIndexOfParam = indexOfParam;
		if ((finalizedIndexOfParam >= 0) != (paramToBeGround != null)) {
			throw new IllegalStateException("Param to be ground is " + paramToBeGround + ", but the index in the literal is " + finalizedIndexOfParam);
		}

		/* determine currently valid candidates */
		EvaluablePredicate predicate = this.evaluablePlanningPredicates.get(l.getPropertyName());

		/* if this param is checked for the first time, aquire an oracle */
		if (paramToBeGround != null) {
			logger.info("No valid grounding for param {} are known, so apply oracle.", paramToBeGround);
			Collection<List<ConstantParam>> possibleGroundingsOfThisPredicate = l.isPositive() ? predicate.getParamsForPositiveEvaluation(state, params) : predicate.getParamsForNegativeEvaluation(state, params);
			if (possibleGroundingsOfThisPredicate == null) {
				logger.warn("Predicate {} returned NULL for params {} in state {}. Canceling grounding process.", l.getPropertyName(), params, state);
				return;
			}
			Collection<ConstantParam> possibleValuesForNewParamInThisGrounding = possibleGroundingsOfThisPredicate.stream().map(s -> s.get(finalizedIndexOfParam)).collect(Collectors.toSet());
			for (ConstantParam oracledParamOfThisLiteral : possibleValuesForNewParamInThisGrounding) {
				Map<VariableParam, ConstantParam> extendedOracleGrounding = new HashMap<>(previouslyOracledGrounding);
				extendedOracleGrounding.put(paramToBeGround, oracledParamOfThisLiteral);
				groundingsFixedSoFar.add(extendedOracleGrounding);
			}
			logger.info("Candidates for grounding is now {}", groundingsFixedSoFar);
			paramsGroundSoFar.add(paramToBeGround);
		}

		/* otherwise just test the predicate against the choices already made */
		else {
			if (logger.isInfoEnabled()) {
				logger.info("No new parameters to ground. Only testing {} (evaluated by {}) against params {} given groundings {}.", l, predicate.getClass().getName(), Arrays.toString(params), groundingsFixedSoFar);
			}
			localCopyOfCurrentGrounding.stream().filter(grounding -> predicate.test(state, params) == l.isPositive()).forEach(groundingsFixedSoFar::add);
		}
	}
	logger.info("Proceeding with extended oracle grounding: {}", groundingsFixedSoFar);
	this.getOracleGroundings(ungroundParamsInEvaluablePrecondition, literalsOrderedByOracability, state, paramsGroundSoFar, groundingsFixedSoFar, basicConstantGrounding);
}