Java Code Examples for java.util.ArrayList.trimToSize()

The following are Jave code examples for showing how to use trimToSize() of the java.util.ArrayList class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: guava-mock   File: Ordering.java   View Source Code Vote up 6 votes
/**
 * Returns the {@code k} least elements from the given iterator according to this ordering, in
 * order from least to greatest. If there are fewer than {@code k} elements present, all will be
 * included.
 *
 * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple
 * elements are equivalent, it is undefined which will come first.
 *
 * <p><b>Java 8 users:</b> Continue to use this method for now. After the next release of Guava,
 * use {@code Streams.stream(iterator).collect(Comparators.least(k, thisComparator))} instead.
 *
 * @return an immutable {@code RandomAccess} list of the {@code k} least elements in ascending
 *     order
 * @throws IllegalArgumentException if {@code k} is negative
 * @since 14.0
 */
public <E extends T> List<E> leastOf(Iterator<E> iterator, int k) {
  checkNotNull(iterator);
  checkNonnegative(k, "k");

  if (k == 0 || !iterator.hasNext()) {
    return ImmutableList.of();
  } else if (k >= Integer.MAX_VALUE / 2) {
    // k is really large; just do a straightforward sorted-copy-and-sublist
    ArrayList<E> list = Lists.newArrayList(iterator);
    Collections.sort(list, this);
    if (list.size() > k) {
      list.subList(k, list.size()).clear();
    }
    list.trimToSize();
    return Collections.unmodifiableList(list);
  } else {
    TopKSelector<E> selector = TopKSelector.least(k, this);
    selector.offerAll(iterator);
    return selector.topK();
  }
}
 
Example 2
Project: ditb   File: ScopeWALEntryFilter.java   View Source Code Vote up 6 votes
@Override
public Entry filter(Entry entry) {
  NavigableMap<byte[], Integer> scopes = entry.getKey().getScopes();
  if (scopes == null || scopes.isEmpty()) {
    return null;
  }
  ArrayList<Cell> cells = entry.getEdit().getCells();
  int size = cells.size();
  for (int i = size - 1; i >= 0; i--) {
    Cell cell = cells.get(i);
    // The scope will be null or empty if
    // there's nothing to replicate in that WALEdit
    if (!scopes.containsKey(cell.getFamily())
        || scopes.get(cell.getFamily()) == HConstants.REPLICATION_SCOPE_LOCAL) {
      cells.remove(i);
    }
  }
  if (cells.size() < size / 2) {
    cells.trimToSize();
  }
  return entry;
}
 
Example 3
Project: jdk8u-jdk   File: Attribute.java   View Source Code Vote up 5 votes
public void trimToSize() {
    if (attributes == null) {
        return;
    }
    if (attributes.isEmpty()) {
        attributes = null;
        return;
    }
    if (attributes instanceof ArrayList) {
        ArrayList<Attribute> al = (ArrayList<Attribute>)attributes;
        al.trimToSize();
        boolean allCanon = true;
        for (Attribute a : al) {
            if (!a.isCanonical()) {
                allCanon = false;
            }
            if (a.fixups != null) {
                assert(!a.isCanonical());
                a.fixups = Fixups.trimToSize(a.fixups);
            }
        }
        if (allCanon) {
            // Replace private writable attribute list
            // with only trivial entries by public unique
            // immutable attribute list with the same entries.
            attributes = getCanonList(al);
        }
    }
}
 
Example 4
Project: openjdk-jdk10   File: Compiler.java   View Source Code Vote up 5 votes
private static List<CompilationPhase> concatPhases(final CompilationPhases[] bases) {
    final ArrayList<CompilationPhase> l = new ArrayList<>();
    for(final CompilationPhases base: bases) {
        l.addAll(base.phases);
    }
    l.trimToSize();
    return l;
}
 
Example 5
Project: sstore-soft   File: ArrayListMultimap.java   View Source Code Vote up 5 votes
/**
 * Reduces the memory used by this {@code ArrayListMultimap}, if feasible.
 */
public void trimToSize() {
  for (Collection<V> collection : backingMap().values()) {
    ArrayList<V> arrayList = (ArrayList<V>) collection;
    arrayList.trimToSize();
  }
}
 
Example 6
Project: yyox   File: ListUtils.java   View Source Code Vote up 5 votes
public static <T> List<T> filter(List<T> list, ListUtilsHook<T> hook) {
    ArrayList<T> r = new ArrayList<T>();
    for (T t : list) {
        if (hook.Result(t)) {
            r.add(t);
        }
    }
    r.trimToSize();
    return r;
}
 
Example 7
Project: OpenJSharp   File: Attribute.java   View Source Code Vote up 5 votes
public void trimToSize() {
    if (attributes == null) {
        return;
    }
    if (attributes.isEmpty()) {
        attributes = null;
        return;
    }
    if (attributes instanceof ArrayList) {
        ArrayList<Attribute> al = (ArrayList<Attribute>)attributes;
        al.trimToSize();
        boolean allCanon = true;
        for (Attribute a : al) {
            if (!a.isCanonical()) {
                allCanon = false;
            }
            if (a.fixups != null) {
                assert(!a.isCanonical());
                a.fixups = Fixups.trimToSize(a.fixups);
            }
        }
        if (allCanon) {
            // Replace private writable attribute list
            // with only trivial entries by public unique
            // immutable attribute list with the same entries.
            attributes = getCanonList(al);
        }
    }
}
 
Example 8
Project: holon-vaadin   File: ViewNavigationUtils.java   View Source Code Vote up 5 votes
/**
 * Get {@link ViewContext} annotated fields of class and its superclasses
 * @param cls Class to inspect
 * @return ViewContext annotated fields
 * @throws ViewConfigurationException Invalid Context injection type
 */
public static Collection<ViewContextField> getContextInjectionFields(Class<?> cls)
		throws ViewConfigurationException {
	ArrayList<ViewContextField> fields = new ArrayList<>();

	Class<?> currentClass = cls;
	while (currentClass != null) {
		final Field[] declaredFields = currentClass.getDeclaredFields();
		for (final Field field : declaredFields) {
			if (field.isAnnotationPresent(ViewContext.class)) {
				// check not final
				if (Modifier.isFinal(field.getModifiers())) {
					throw new ViewConfigurationException("Context injection field " + field.getName()
							+ " must not be declared as final in class " + cls.getName());
				}
				ViewContext vc = field.getAnnotation(ViewContext.class);

				fields.add(
						ViewContextField.build(AnnotationUtils.getStringValue(vc.value()), vc.required(), field));
			}
		}
		currentClass = currentClass.getSuperclass();
	}

	fields.trimToSize();
	return fields;
}
 
Example 9
Project: zerocell   File: EntityHandler.java   View Source Code Vote up 5 votes
private ColumnMapping readColumnInfoViaReflection(Class<?> clazz) {
    Field[] fieldArray = clazz.getDeclaredFields();
    ArrayList<ColumnInfo> list = new ArrayList<>(fieldArray.length);
    ColumnInfo rowNumberColumn = null;
    for (Field field: fieldArray) {

        RowNumber rowNumberAnnotation = field.getAnnotation(RowNumber.class);

        if (! Objects.isNull(rowNumberAnnotation)) {
            rowNumberColumn = new ColumnInfo("__id__", field.getName(), -1, null,Integer.class, NoopConverter.class);
            continue;
        }

        Column annotation = field.getAnnotation(Column.class);
        if (! Objects.isNull(annotation)) {
            Class<?> converter = annotation.convertorClass();
            list.add(new ColumnInfo(annotation.name().trim(),
                    field.getName(),
                    annotation.index(),
                    annotation.dataFormat(),
                    field.getType(),
                    converter));
        }
    }

    if (list.isEmpty()) {
        throw new ZeroCellException(String.format("Class %s does not have @Column annotations", clazz.getName()));
    }
    list.trimToSize();
    return new ColumnMapping(rowNumberColumn, list);
}
 
Example 10
Project: etomica   File: ClusterOperations.java   View Source Code Vote up 5 votes
/**
 * Replaces all isomorphic clusters in the given list by a single cluster
 * with weight given by their sum.  The resulting list is also sorted by #
 * of connections.  Both the list and the the weights of the clusters it
 * contains may be altered by this method.
 */
public static void addEquivalents(ArrayList<ClusterDiagram> list) {
    if (list.size() < 2) {
        return;
    }
    reduce(list);
    ClusterDiagram cluster1 = null;
    for (int i=0; i<list.size(); i++) {
        cluster1 = list.get(i);
        for (int j=i+1; j<list.size(); j++) {
            ClusterDiagram cluster2 = list.get(j);
            if (cluster1.getNumConnections() != cluster2.getNumConnections()) {
                break;
            }
            if(cluster2.getWeight().numerator() == 0) {
                continue;
            }
            if(cluster1.isIsomorphOf(cluster2)) {
                int[] score1 = new int[cluster1.mNumBody/2+1];
                cluster1.calcScore(score1);
                if(cluster2.scoreGreaterThan(score1)) {
                    cluster2.setWeight(cluster1.getWeight().plus(cluster2.getWeight()));
                    cluster1.setWeight(Rational.ZERO);
                    break;
                }
                cluster1.setWeight(cluster1.getWeight().plus(cluster2.getWeight()));
                cluster2.setWeight(Rational.ZERO);
            }
        }
    }
    //remove clusters having zero weight
    for (int i=0; i<list.size(); i++) {
        ClusterDiagram cluster = list.get(i);
        if(cluster.getWeight().numerator() == 0) {
            list.remove(i);
            i--;
        }
    }
    list.trimToSize();
}
 
Example 11
Project: openjdk-jdk10   File: Parser.java   View Source Code Vote up 5 votes
private static <T> List<T> optimizeList(final ArrayList<T> list) {
    switch(list.size()) {
        case 0: {
            return Collections.emptyList();
        }
        case 1: {
            return Collections.singletonList(list.get(0));
        }
        default: {
            list.trimToSize();
            return list;
        }
    }
}
 
Example 12
Project: myfaces-trinidad   File: RenderKitTestCase.java   View Source Code Vote up 5 votes
/**
 * Utility function for returning the subset of the availableDefinitions in availableDefinitions
 * order, with categories named in the allowedDefinitionNames.  If availableDefinitions is
 * empty, no filtering is performed.
 * @param allowedDefinitionNames
 * @param availableDefinitions
 * @return
 */
protected static List<SuiteDefinition> filterDefinitions(
  Set<String> allowedDefinitionNames, List<SuiteDefinition> availableDefinitions)
{    
  if (allowedDefinitionNames.isEmpty())
  {
    return availableDefinitions;
  }
  else
  {
    ArrayList<SuiteDefinition> definitions = new ArrayList<SuiteDefinition>();
    
    for (String category : allowedDefinitionNames)
    {
      SuiteDefinition allowedDefinition = _getSuitedDefinitionByCategory(availableDefinitions, category);
      
      if (allowedDefinition != null)
      {
        definitions.add(allowedDefinition);
      }
      else
      {
        _LOG.warning("Unabled to find test category named:" + category);
      }
    }

    definitions.trimToSize();
    return Collections.unmodifiableList(definitions);
  }
}
 
Example 13
Project: s-store   File: ArrayListMultimap.java   View Source Code Vote up 5 votes
/**
 * Reduces the memory used by this {@code ArrayListMultimap}, if feasible.
 */
public void trimToSize() {
  for (Collection<V> collection : backingMap().values()) {
    ArrayList<V> arrayList = (ArrayList<V>) collection;
    arrayList.trimToSize();
  }
}
 
Example 14
Project: MaxSim   File: VirtualMachineImpl.java   View Source Code Vote up 5 votes
private List getPath (String pathName) {
    String cp = saVM.getSystemProperty(pathName);
    String pathSep = saVM.getSystemProperty("path.separator");
    ArrayList al = new ArrayList();
    StringTokenizer st = new StringTokenizer(cp, pathSep);
    while (st.hasMoreTokens()) {
        al.add(st.nextToken());
    }
    al.trimToSize();
    return al;
}
 
Example 15
Project: intellij-deps-trove4j   File: MemoryUsage.java   View Source Code Vote up 5 votes
@Override
public Object create() {
    ArrayList list = new ArrayList();
    for (int i = 0; i < 1000; i++) {
        Integer x = new Integer(i);
        list.add(x);
    }
    list.trimToSize();
    return list;
}
 
Example 16
Project: apache-tomcat-7.0.73-with-comment   File: DirContextURLConnection.java   View Source Code Vote up 4 votes
/**
 * Returns an unmodifiable Map of the header fields.
 */
@Override
public Map<String,List<String>> getHeaderFields() {

  if (!connected) {
      // Try to connect (silently)
      try {
          connect();
      } catch (IOException e) {
          //Ignore
      }
  }

  if (attributes == null)
      return (Collections.emptyMap());

  HashMap<String,List<String>> headerFields =
      new HashMap<String,List<String>>(attributes.size());
  NamingEnumeration<String> attributeEnum = attributes.getIDs();
  try {
      while (attributeEnum.hasMore()) {
          String attributeID = attributeEnum.next();
          Attribute attribute = attributes.get(attributeID);
          if (attribute == null) continue;
          ArrayList<String> attributeValueList =
              new ArrayList<String>(attribute.size());
          NamingEnumeration<?> attributeValues = attribute.getAll();
          while (attributeValues.hasMore()) {
              Object attrValue = attributeValues.next();
              attributeValueList.add(getHeaderValueAsString(attrValue));
          }
          attributeValueList.trimToSize(); // should be a no-op if attribute.size() didn't lie
          headerFields.put(attributeID, Collections.unmodifiableList(attributeValueList));
      }
  } catch (NamingException ne) {
        // Shouldn't happen
  }

  return Collections.unmodifiableMap(headerFields);

}
 
Example 17
Project: hadoop   File: AclTransformation.java   View Source Code Vote up 4 votes
/**
 * Builds the final list of ACL entries to return by trimming, sorting and
 * validating the ACL entries that have been added.
 *
 * @param aclBuilder ArrayList<AclEntry> containing entries to build
 * @return List<AclEntry> unmodifiable, sorted list of ACL entries
 * @throws AclException if validation fails
 */
private static List<AclEntry> buildAndValidateAcl(
    ArrayList<AclEntry> aclBuilder) throws AclException {
  if (aclBuilder.size() > MAX_ENTRIES) {
    throw new AclException("Invalid ACL: ACL has " + aclBuilder.size() +
      " entries, which exceeds maximum of " + MAX_ENTRIES + ".");
  }
  aclBuilder.trimToSize();
  Collections.sort(aclBuilder, ACL_ENTRY_COMPARATOR);
  // Full iteration to check for duplicates and invalid named entries.
  AclEntry prevEntry = null;
  for (AclEntry entry: aclBuilder) {
    if (prevEntry != null &&
        ACL_ENTRY_COMPARATOR.compare(prevEntry, entry) == 0) {
      throw new AclException(
        "Invalid ACL: multiple entries with same scope, type and name.");
    }
    if (entry.getName() != null && (entry.getType() == MASK ||
        entry.getType() == OTHER)) {
      throw new AclException(
        "Invalid ACL: this entry type must not have a name: " + entry + ".");
    }
    prevEntry = entry;
  }
  // Search for the required base access entries.  If there is a default ACL,
  // then do the same check on the default entries.
  ScopedAclEntries scopedEntries = new ScopedAclEntries(aclBuilder);
  for (AclEntryType type: EnumSet.of(USER, GROUP, OTHER)) {
    AclEntry accessEntryKey = new AclEntry.Builder().setScope(ACCESS)
      .setType(type).build();
    if (Collections.binarySearch(scopedEntries.getAccessEntries(),
        accessEntryKey, ACL_ENTRY_COMPARATOR) < 0) {
      throw new AclException(
        "Invalid ACL: the user, group and other entries are required.");
    }
    if (!scopedEntries.getDefaultEntries().isEmpty()) {
      AclEntry defaultEntryKey = new AclEntry.Builder().setScope(DEFAULT)
        .setType(type).build();
      if (Collections.binarySearch(scopedEntries.getDefaultEntries(),
          defaultEntryKey, ACL_ENTRY_COMPARATOR) < 0) {
        throw new AclException(
          "Invalid default ACL: the user, group and other entries are required.");
      }
    }
  }
  return Collections.unmodifiableList(aclBuilder);
}
 
Example 18
Project: lazycat   File: DirContextURLConnection.java   View Source Code Vote up 4 votes
/**
 * Returns an unmodifiable Map of the header fields.
 */
@Override
public Map<String, List<String>> getHeaderFields() {

	if (!connected) {
		// Try to connect (silently)
		try {
			connect();
		} catch (IOException e) {
			// Ignore
		}
	}

	if (attributes == null)
		return (Collections.emptyMap());

	HashMap<String, List<String>> headerFields = new HashMap<String, List<String>>(attributes.size());
	NamingEnumeration<String> attributeEnum = attributes.getIDs();
	try {
		while (attributeEnum.hasMore()) {
			String attributeID = attributeEnum.next();
			Attribute attribute = attributes.get(attributeID);
			if (attribute == null)
				continue;
			ArrayList<String> attributeValueList = new ArrayList<String>(attribute.size());
			NamingEnumeration<?> attributeValues = attribute.getAll();
			while (attributeValues.hasMore()) {
				Object attrValue = attributeValues.next();
				attributeValueList.add(getHeaderValueAsString(attrValue));
			}
			attributeValueList.trimToSize(); // should be a no-op if
												// attribute.size() didn't
												// lie
			headerFields.put(attributeID, Collections.unmodifiableList(attributeValueList));
		}
	} catch (NamingException ne) {
		// Shouldn't happen
	}

	return Collections.unmodifiableMap(headerFields);

}
 
Example 19
Project: OpenJSharp   File: Compiler.java   View Source Code Vote up 4 votes
private static <T> List<T> concat(final List<T> l1, final List<T> l2) {
    final ArrayList<T> l = new ArrayList<>(l1);
    l.addAll(l2);
    l.trimToSize();
    return l;
}
 
Example 20
Project: diorite-configs-java8   File: DeserializationData.java   View Source Code Vote up 3 votes
/**
 * Deserialize list on given key, if key contains Map instead of List, it will be deserialized and returned as list of values.<br>
 * Use empty key to deserialize map from root element.
 *
 * @param key
 *         value to deserialize.
 * @param type
 *         type of elements.
 * @param <T>
 *         type of elements.
 *
 * @return deserialized value.
 */
default <T> List<T> getAsList(String key, Class<T> type)
{
    ArrayList<T> objects = new ArrayList<>(20);
    this.getAsCollection(key, type, objects);
    objects.trimToSize();
    return objects;
}