GithubHelp home page GithubHelp logo

google-collections's People

Contributors

cpovirk avatar

Watchers

 avatar  avatar

google-collections's Issues

a new factory-method on Lists class

Hi,

I want a list index-based then I did this function:
  public static <E> ArrayList<E> newArrayList(
                  int size, Function<Integer, E> function) {
    checkNotNull(function);
    int capacity = computeArrayListCapacity(size);
    ArrayList<E> list = new ArrayList<E>(capacity);
    for (int i = 0; i < size; i++) {
        list.add(function.apply(i));
    }
    return list;
  }

Now, I can to create a list with the 1000 first natural numbers with the
following code:
List<Integer> numbers = Lists.newArrayList(1000,                          
    Functions.<Integer>identity());

What do you think about it?

Original issue reported on code.google.com by [email protected] on 20 Oct 2007 at 2:10

filter(Collection) returning a Collection

There's no reason not to allow viewing a Collection, filtered, as another
Collection, except that size() and isEmpty() of the view become O(n).

I believe we should do this.  This would also take care of issue 45.

Original issue reported on code.google.com by [email protected] on 30 Jan 2008 at 5:13

putAll in StandardMultimap doesn't add an entry when empty collection is passed

IMO the putAll on Multimaps should create always create an entry in the
keySet of the map, even when an empty collection or null is passed.

The reason I post this issue can be easily described by following code (I
came across a bug in our application that had the same logic - I simplified
it here)

Multimap<String, String> synonyms = Multimaps.newHashMultimap();
final String helloString = "hello";

//assume the synonymManager doesn't know any synonyms, 
//so an empty collection is returned
synonyms.putAll(helloString, synonymManager.getSynonyms(helloString));

this.printSynonyms(synonyms);

//when i want to print out the list, I wanted to show "hello" and next to
//it the synonyms. When there are no synonyms, I want to print out blank
//space

Obviously my issue was a lot complexer, but I hope you can see my problem...


Original issue reported on code.google.com by [email protected] on 17 Dec 2007 at 11:13

UniqueList<E>

A UniqueList is a List which rejects duplicate elements (recall that the
modification methods on List, add/add/addAll/addAll/set, are permitted
throw IllegalArgumentException if there's anything they don't like about
the offered element(s)). The same goes for the modification methods on the
list's listIterator().

The nice thing about this restriction is that a UniqueList can be viewed as
a Set in a completely "read-through, write-through" fashion.  So the
UniqueList<E> interface would extend List<E> to add this asSet() method. I
don't believe that any subtype of Set is needed for this; AFAIK it just
needs regular Set methods and not much else.

As well, the subList() method could be refined so that it also returns a
UniqueList<E>. Of course, the sublist would throw IAE in response to any
operation that would result in a duplicate element in the *parent* list.

An AbstractUniqueList<E> class could be provided which only needs the
implementing class to supply a backing List and a backing Set, and
optionally override a few methods for better performance.

Unfortunately, the Collections methods sort(), shuffle(), reverse() and
swap() would fail on a UniqueList. They all make the assumption that the
list being acted upon has no problem with temporarily containing the same
element twice.  There's nothing we can do about that -- it's the price you pay.

Original issue reported on code.google.com by [email protected] on 23 Oct 2007 at 4:14

omnibus issue for added Iterators/Iterables functionality

Iterables/Iterators lacks:

* size(Iter)/count(Iter)
* elementAt(Iter,int)
* elementAtPercentile(Iter,double)
* randomElement(Iter)
* contains(Iter,Object)
* removeFirst(Iter,Object)
* removeAll(Iter,Object)
* truncate(Iter,int)
* narrow(Iter) [see Functions for an example]
* index(Iter) [yields an IndexedIterator having an index() method]

The Iterables forms would, as usual, use special-case logic depending on
what type of iterable it is, so we don't do anything slower than we had to.
For example finding the element at position 99999 in a Multiset should not
actually iterate the whole thing, but should make use of the entrySet().

Clearly we've survived ok without these so far, but I'm throwing them out
here to collect input on which might be more important to you than others.

Original issue reported on code.google.com by [email protected] on 23 Oct 2007 at 5:04

Standardize how to create instances of JDK 5 collections

First I'll list the specific changes I propose to make, then provide the
full justification below.

Drop:

1. Lists.newArrayListWithCapacity(int)
2. Lists.newLinkedList(Iterator)
3. Lists.newLinkedList(E...)
4. Sets.newLinkedHashSet(Iterator)
5. Sets.newLinkedHashSet(E...)

Add:

1. Lists.newCopyOnWriteArrayList()
2. Lists.newCopyOnWriteArrayList(Iterable)
3. Sets.newCopyOnWriteArraySet()
4. Sets.newCopyOnWriteArraySet(Iterable)
5. Maps.newTreeMap(Map)
6. Maps.newConcurrentHashMap(Map)
7. Maps.newEnumMap(Map)

------

With the lone exception of EnumSet, JDK collections lack useful static
creation methods like

  ArrayList.newInstance()
  ArrayList.newInstance(Iterable)
  etc.

These are important to have for a few reasons:

1. Provided copy constructors require Collection, not permitting Iterable,
varargs, etc.

2. The language spec failed to provide type inference for constructors in
the same way it does for static methods.

We are providing these in our classes called Lists, Sets, and Maps.  (Still
no support for Queues, but I'll file that separately.)  The problem is that
we are wildly inconsistent in what we choose to provide and not to provide.

I propose that we follow these conventions:

For each major interface type, there is one clearly dominant implementation
(ArrayList, HashSet, and HashMap). For these implementations, we should
provide the full complement of creation methods.  For Collection types
these are

1. No parameters
2. Iterable
3. Iterator
4. Varargs/array
5. With sizing parameters

For Map these are

1. No parameters
2. Map
3. With sizing parameters

Then there are the sorted types, which likewise have their dominant
implementations TreeSet and TreeMap.

For TreeSet we should have

1. No parameters
2. Iterable
3. Iterator
4. Varargs/array
5. With comparator
6+:  open issue. should *all* be repeated with comparator? none, or
something in between?

and for TreeMap

1. No parameters
2. Map (copy constructor)
3. With comparator
4. open issue: with both?

Then there are the secondary implementations:

sequential:  LinkedList, LinkedHashSet, LinkedHashMap
concurrent: CopyOnWriteArrayList, CopyOnWriteArraySet, ConcurrentHashMap
enum: EnumSet, EnumMap (but EnumSet doesn't need our help)
weird: IdentityHashMap

For these, I suggest that we provide only the basics.

1. No parameters
2. Iterable/Map copy-constructor (and not even that for IHM)

These would not have the Iterator and varargs forms, and the caller can
make use of Iterators.addAll(), Collections.addAll() and/or Arrays.asList()
to get this functionality.

These would also not have tuning parameters (though I am considering making
an exception for ConcurrentHashMap).

Original issue reported on code.google.com by [email protected] on 31 Oct 2007 at 8:26

ReferenceMap's SoftValueReference, WeakValueReference .toString() methods not overridden

These internal classes in ReferenceMap throw AssertionErrors if their
hashCode() methods are invoked (ReferenceMap.java lines 540 and 584).  I'm
assuming this is because they are not intended to be used as map keys.  But
the default toString() method (it's not overridden in either case) invokes
this.hashCode(), so attempting to print these objects throws an
AssertionError as well.

I'm passing in a delegate ConcurrentHashMap in ReferenceMap's constructor
and overriding its remove() methods so that I know when an entry is removed
from the map.  I discovered this bug when I was doing a simple
System.out.println() on the values being removed.

Thanks,
Laird (ljnelson over at gmail.com)

Original issue reported on code.google.com by ljnelson on 13 Nov 2007 at 9:04

Req: Abstraction of MultiMap to handle arbitrary op and basecase (identity-under-op)

I frequently need to find the max / total / avg value for each key, across
a set of key / value pairs.  Here is a static method to accomplish this for
max:

    public static void mapPutMax(HashMap<String, Integer> map, String key, int
newVal) {
        int max = newVal;
        if (map.containsKey(key))
            max = Math.max(map.get(key), max);
        map.put(key, max);
    }

In the same way that a MultiMap greatly facilitates a pattern similar to
the above when adding an entry to a Map<String, List> (i.e. creating a new
empty ArrayList if the key doesn't yet exist in the map, else appending to
the existing list), it would be great if there were an abstraction of
MultiMap, called say MapBuilder, which allowed you to define an add
operation and an identity under the operation when no value yet exists for
a given key.  Something like the following:


    public class MapBuilder<K, V, Velem> {
        // Can't just extend HashMap<K, V> because we need put(K, Velem) not
put(K, V)
        private HashMap<K, V> underlyingMap = new HashMap<K, V>();
        private MapBuilderOp<V, Velem> op;

        public MapBuilder() {
            throw new IllegalArgumentException("Cannot use default constructor");
        }

        public MapBuilder(MapBuilderOp<V, Velem> op) {
            this.op = op;
        }

        public V getValOrIdentity(K key) {
            return (underlyingMap.containsKey(key) ? underlyingMap.get(key) :
this.op.newIdentityUnderOp());
        }

        public V get(K key) {
            return underlyingMap.get(key);
        }

        public V put(K key, Velem val) {
            V newVal = this.op.applyLeftAssoc(getValOrIdentity(key), val);
            return underlyingMap.put(key, newVal);
        }

        public Set<K> keySet() {
            return underlyingMap.keySet();
        }
    }

This would be used as follows: 

    MapBuilder<String, Integer, Integer> map1 = new Main().new
MapBuilder<String, Integer, Integer>(new MapBuilderOp<Integer, Integer>() {
        @Override
        public Integer applyLeftAssoc(Integer oldVal, Integer newVal) {
            return oldVal * newVal;
        }
        @Override
        public Integer newIdentityUnderOp() {
            return 1;
        }
    });
    map1.put("a", 2);
    map1.put("b", 2);
    map1.put("a", 10);
    map1.put("b", 1);
    map1.put("a", 7);
    for (String k : map1.keySet())
        System.out.println(k + " " + map1.get(k));

    MapBuilder<String, ArrayList<Integer>, Integer> map2 = new Main().new
MapBuilder<String, ArrayList<Integer>, Integer>(new
MapBuilderOp<ArrayList<Integer>, Integer>() {
        @Override
        public ArrayList<Integer> applyLeftAssoc(ArrayList<Integer> oldList,
Integer newVal) {
            // This is a problem, we should really just return a copy of oldList
with newVal appended, but
            // doing this in-place is much faster.  Perhaps implement different
method for in-place
            // modification?
            oldList.add(newVal);
            return oldList;
        }
        @Override
        public ArrayList<Integer> newIdentityUnderOp() {
            return new ArrayList<Integer>();
        }
    });

    map2.put("a", 2);
    map2.put("b", 2);
    map2.put("a", 10);
    map2.put("b", 1);
    map2.put("a", 7);
    for (String k : map2.keySet())
        System.out.println(k + ": " + Join.join(", ", map2.get(k)));

(There could also be a version of MapBuilder with type <K, V>, for when V
== Velem, that will simplify usage in the case of map1 above.)


You can see that in the case of map2, we actually have an implementation of
a MultiMap; in the case of map1, we can use different identities and
operations according to what sort of math we are applying, for example:

ident   op   action
  1     *    prod
  0     +    sum
 null   fn    max   , where fn = (oldVal == null ? newVal :
Math.max(oldVal, newVal)


This therefore represents a useful abstraction of MultiMap to a much
broader range of use cases.

Thanks!

Original issue reported on code.google.com by luke.hutch on 28 Nov 2007 at 11:05

Python-style zip and enumerate methods

Two Iterator/Iterable/Collection related methods I seem to be
reimplementing all the time in various languages are zip and enumerate from
Python.

Here's their documentation from CPython 2.5. zip:

    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated
    in length to the length of the shortest argument sequence.

And enumerate:

   enumerate(iterable) -> iterator for index, value of iterable

   Return an enumerate object.  iterable must be an other object that supports
   iteration.  The enumerate object yields pairs containing a count (from
   zero) and a value yielded by the iterable argument.  enumerate is useful
   for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...

I've implemented these in a MIT-licensed library for Java, JIterTools, at
http://www.juripakaste.fi/jitertools/ . They operate on Iterators and
Iterables. There's also a variant of zip called zipFill that goes on as
long as there are items in one of the Iterables/Iterators, reading extra
values for exhausted Iterators from an associated function. 

I'd love to see all of them/some of them/something like them included in a
well-maintained library of various Collection related things and Google
Collections looks like a prime candidate as long as Commons Collections is
inactive. I'm not particular about the exact details, though. Of the
methods I've implemented, zip is the cleanest with no extra classes needed
for parameters or return values. Both enumerate and zipFill need helper
classes.



Original issue reported on code.google.com by [email protected] on 4 Nov 2007 at 12:27

Maps.uniqueIndex should size the new Map better

Maps.uniqueIndex sizes the new collection based on the size of the list, when 
it should could call 
capacity on the list.

Line 508 should read
      newMap = new HashMap<K, V>(capacity(collection.size()));


Original issue reported on code.google.com by [email protected] on 20 Jan 2008 at 4:57

StandardMultimap$RandomAccessWrappedList is not Serializable

Hi
I got this exception:
    java.io.NotSerializableException:
com.google.common.collect.StandardMultimap$RandomAccessWrappedList
java.rmi.MarshalException: error marshalling arguments; nested exception is: 
    java.io.NotSerializableException:
com.google.common.collect.StandardMultimap$RandomAccessWrappedList
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:122)
at org.jboss.invocation.jrmp.server.JRMPInvoker_Stub.invoke(Unknown Source)
....

Which is surprising, why shouldn't this RandomAccessWrappedList be
Serializable?

I have a ListMultimap<String,Enum> and I need to send the list of enums to
my EJB Server. It worked fine when I was using a HashMap<String,List<Enum>>.

List<Enum> = myMultimap.get(state);
This list is not serializable.

Is it by design?

Thanks
Benoit.

Original issue reported on code.google.com by [email protected] on 6 Nov 2007 at 3:49

BloomFilter<E>

A BloomFilter is a useful data structure.

  http://en.wikipedia.org/wiki/Bloom_filter

Proposed straw-man API follows.  It shares only four methods in common with
Collection, and adds two of its own.

/**
 * A probabilistic "shadow" of a set of elements, useful
 * when the set itself would be too expensive to maintain in
 * memory and query directly. A Bloom filter can give false
 * positivites, but never false negatives. That is, adding
 * an element to the filter guarantees that {@link
 * #mightContain} will return {@code true}, but {@link
 * #mightContain} returning {@code true} does not guarantee
 * that this element was ever actually added to the filter.
 */
public final class BloomFilter<E> implements Serializable {
  /**
   * Returns {@code true} if it is <i>possible</i>
   * (probability nonzero) that {@code element} is contained
   * in the set represented by this Bloom filter.  If this
   * method returns {@code false}, this element is
   * <i>definitely</i> not present. If it {@code true}, the
   * probability that this element has <i>not</i> actually
   * been added is given by {@link
   * #getFalsePositiveProbability()}.
   */
  public boolean mightContain(@Nullable E element) { ... }

  /**
   * Returns the probability that {@link #mightContain} will
   * return {@code true} for an element not actually
   * contained in this set.
   */
  public double getFalsePositiveProbability() { ... }

  /**
   * Adds {@code newElement} to this Bloom filter, so that
   * {@code mightContain(newElement)} is now guaranteed to
   * return {@code true}.
   *
   * @return true if the Bloom filter changed as a result of
   * this call
   */
  public boolean add(@Nullable E newElement) { ... }

  // self-explanatory methods:
  public boolean addAll(Iterable<? extends E> elements) { ... }
  public boolean isEmpty() { ... }
  public void clear() { ... }
}

Original issue reported on code.google.com by [email protected] on 23 Oct 2007 at 4:02

Lists.immutableList(Iterable) should be named distinctly from immutableList(E) ; (E...)

The com.google.common.collect.Lists class has methods immutableList(E) and
immutableList(Iterable<? extends E>).

They don't comply with Joshua Bloch's recommendations for method
overloading: 
http://www.informit.com/content/images/0201310058/samplechapter/blochch6.pdf

So in order to make an immutable list of a single Iterable one has to use
casting: (List<Iterable>) Lists.immutableList((Object) myIterable)

Furthermore, they don't work with Retrotranslator that replaces both
parameter types with Object and removes one duplicate method after that.

Maybe it would make sense to rename one of the methods.

Original issue reported on code.google.com by [email protected] on 11 Oct 2007 at 2:20

Copy arbitrary collections

Currently we can't really do this:
   Map<Customer> original = ...
   Map<Customer> copy = Maps.copyOf(original);

Because we don't know the runtime type of original. I propose the following:
  1. Introduce a Copyable<T> interface that allows Collections (and possibly other types) to 
provide shallow copies of themselves.
  2. Implement said interface for all collections in the API
  3. Create APIs that can copy an arbitrary Collections. For things that implement Copyable, this 
would use that. For the known set of collections in the JDK, this would copy 
these using the 
most appropriate mechanism. For everything else, this should fail with a 
RuntimeException.

Difficult stuff:
- deep vs. shallow copies. For collections, I believe shallow copies are best. 
I 'm not ready to 
expand the copyable interface to anything else.
- wrapped collections. How to copy a TreeMap that's been wrapped with 
unmodifiableMap?
- other views. What do we do when we copy the keySet of a TreeMap?

Original issue reported on code.google.com by limpbizkit on 1 Nov 2007 at 2:06

Req: KeyValue iterator

I frequently repeat code like the following:

for (key : map.keySet()) {
  V val = map.get(key);
  System.out.println(key + ": " + val)
}

It would be great if there were a KeyValue iterator for all collections,
that would do this boilerplate work:

for (keyVal : Iterators.keyValIterator(map)) { // or just map.keyValIter()
  System.out.println(keyVal.key + ": " + keyVal.val);
}


Original issue reported on code.google.com by luke.hutch on 28 Nov 2007 at 11:11

newClassToInstanceMap is not serializable

What steps will reproduce the problem?

ClassToInstanceMap<Object> map = Maps.newClassToInstanceMap();
        new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(map);

What is the expected output? What do you see instead?

java.io.NotSerializableException: com.google.common.collect.Maps$2
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1156)
.. etc

What version of the product are you using? On what operating system?

Using recent snapshot.

Original issue reported on code.google.com by nickhowes on 16 Oct 2007 at 11:31

Methods on Sets class: union(), intersection(), difference()

I doubt I'll be the only person saying that it sure would be nice to
finally have these methods.  Aren't they just about the most fundamental
things that one does with a Set?  It feels way overdue to have them supported.

I have these coded up already, but there are Issues.  Josh says, "run away.
run far away" which sounds pretty ominous.

There is one gigantic problem.  The caller will undoubtedly expect the
method to do "the right thing" and return a TreeSet if his inputs were
TreeSets, a LinkedHashSet if his inputs were LHS's, etc., and this is
next-to-impossible to accomplish in any reasonable way.

We'd love to be able to just clone the first Set given and then modify the
clone.  But clone is broken to a point of hopelessness.  The only way we
could possibly even hope to use clone would be via reflection.  That code
was written, but it feels very wrong.

So the alternate approach is to return a Set which is a *view* of the
union/intersection/difference of the two input Sets.  Then the caller can
either use that view directly, or copy the contents out into the desired
concrete collection type from there. This sidesteps a lot of issues, as the
collection code we write primarily just delegates to the input collections.
 Again, I wrote all the code to do this, and I'm just sitting on it.

Very Bad Things may result if you take a TreeSet whose comparator is
inconsistent with equals(), and then try to union() it with a plain old
HashSet. This may be part of where Josh's concern comes from.  However, my
goal is not to prevent people from shooting themselves in the foot using
our library.  My goal is to make sure that if they do shoot themselves in
the foot, well, they really had to have aimed first.  (And why are you
aiming at your foot, people??)

Original issue reported on code.google.com by [email protected] on 23 Oct 2007 at 4:43

quickselect?

If it is desired, we could provide an implementation of the quickselect
algorithm.

  public static <C extends Comparable> List<C> quickSelect(
    List<C> list, int count) {}

  public static <T> List<T> quickSelect(
    List<T> list, Comparator<? super T> comparator, int count) {}

I have some code written, but not tested, debugged etc.  I would only
bother to finish it up if people actually want it.

More on quickselect: http://en.wikipedia.org/wiki/Quick_select

Original issue reported on code.google.com by [email protected] on 31 Oct 2007 at 8:50

method to add to and return count on Multiset

Nice to be able to retrieve the count with add.

So,

multiset.add(key);
int count multiset.count(key)

becomes

int count = multiset.addAndGet(key);

also,
int count = multiset.getAndAdd(key);
int count = multiset.addAndGet(key, occurrences);
int count = multiset.getAndAdd(key, occurrences);


Thanks!

Original issue reported on code.google.com by steven.marcus on 22 Feb 2008 at 11:20

PatriciaTrie Contribution

This is a contribution of LimeWire's PatriciaTrie, as discussed at: 
http://groups.google.com/group/google-
guice/browse_frm/thread/ffb2a3b3b9e39e79?tvc=1 .

The files can be licensed as necessary (we own the copyright and can 
change/transfer the license).  I'm not sure what license, if any, these 
would need to be for inclusion.

Original issue reported on code.google.com by sberlin on 24 Sep 2007 at 6:12

Attachments:

ForwardingObject should use generics

Why not have ForwardingObject have a generic definition, instead of returning 
java.lang.Object from 
delegate()?

public abstract class ForwardingObject<T> implements Serializable {
    public T delegate() { return delegate; }
}

Original issue reported on code.google.com by [email protected] on 24 Oct 2007 at 7:46

Comparators.reverse(Comparator)

It would be useful to have a method in Comparators for creating a
"reversed" comparator, i.e. a comparator that produces order that is
reverse of the comparator given as an argument.

Original issue reported on code.google.com by [email protected] on 25 Nov 2007 at 3:11

Add 'flatMap' (flatTransform?) operation

Scala's collections library has an operation called 'flatMap' on its
sequence type.  It is described as:

override def flatMap[B](f : (A) => Iterable[B]) : Seq[B]

    Applies the given function f to each element of this sequence, then
concatenates the results.

I believe I've seen something similar in the ML libraries and in Haskell.

Here's a naive simple implementation:

    public static <A, B> Collection<B> flatTransform(Iterable<A>
collection, Function<A, Iterable<B>> functor) {
        ArrayList<B> results = Lists.newArrayList();
        for (A a : collection) {
            Iterable<B> result = functor.apply(a);
            Iterables.addAll(results, result);
        }

        return results;
    }

Original issue reported on code.google.com by ryan.daum on 1 Nov 2007 at 11:36

Predicates.forFunction(Function<T, Boolean>)

  /**
   * Returns a predicate that evaluates to the same result as the
   * given function.
   */
  public static <T> Predicate<T> forFunction(
      final Function<T, Boolean> predicate) {
    checkNotNull(predicate);
    return new FunctionPredicate<T>(predicate);
  }

  /** @see Predicates#forFunction(Function) */
  private static class FunctionPredicate<T>
      implements Predicate<T>, Serializable {
    private final Function<T, Boolean> function;

    private FunctionPredicate(final Function<T, Boolean> function) {
      this.function = function;
    }

    public boolean apply(final T t) {
      return Boolean.TRUE.equals(function.apply(t));
    }

    private static final long serialVersionUID = -4940925077935486606L;
  }

Usage examples:
  private static final Predicate<Object> ALWAYS_TRUE =
      forFunction(Functions.constant(Boolean.TRUE));

  private static final Predicate<Object> ALWAYS_FALSE =
      forFunction(Functions.constant(Boolean.FALSE));

Original issue reported on code.google.com by [email protected] on 23 Oct 2007 at 7:06

Method like Constraints.constrainedList which applies to existing elements

The List returned by Constraints.constrainedList still allows 
unconstrained access to elements using List.get().

I would love a method like constrainedList which applies to the existing 
elements of the source list so that get can be used on the list.
I couldn't find this functionality in the library (which is really useful 
for me, btw).

I attached a quick hack which shows what I mean. This solution is not 
implementing a view of the source list. Of course, there are probably 
better solutions. But I couldn't think of a good one right now :)

Original issue reported on code.google.com by [email protected] on 25 Nov 2007 at 8:09

Attachments:

Chained put() calls on a builder cause stack overflow very quickly in some environments

This is not necessarily a bug, per se, in collections, but chaining calls
can cause a stack overflow, and in some environments it happens with
relatively few calls.

Getting a stack overflow during the compilation phase, particularly when
failure is highly dependent on the environment but it not necessarily
related to memory is a very confusing and difficult to debug problem. I
recommend that documentation for the builders make clear note of the
constraint, since at present they mainly demonstrate the ease of using
chained calls.

I haven't had time to do extensive tests to find the cut-off point, but
here are some notes from my experience:

-- With Sun's 1.6 and 1.5 compilers, stack overflow occurs somewhere below
200 chained put() calls on Windows XP using ImmutableBiMapBuilder with an
enum for both keys

-- Changing heap and other memory settings to very high values (up to 1GB
for some settings) does not resolve the problem

-- The same code compiles with Sun's 1.5 compiler on Linux systems without
any changes to default memory settings. JDK 1.6 was not tested on Linux for
this code

-- The same code compiles within Eclipse without any changes to default
memory settings. This causes a large part of debugging confusion

-- Although in retrospect it is clear that the stack-based JVM could have
problems in this respect, I would argue the busy programmer is quite
unlikely to consider alternatives to a huge chain when all the examples
tout the readability

-- "Functional is the New OOP" Observation: This is a great chance for
people unfamiliar with ideas such as tail call recursion to learn what it
is all about

-- "I Will Drink Your Milkshake" Observation: Presumably non-stack JVM-like
environments, such as Dalvik, do not suffer from this condition. This
brings interesting thoughts to mind about why Google wrote Google
Collections in the first place ;-)


Original issue reported on code.google.com by [email protected] on 8 Jan 2008 at 4:02

Upload to Maven repository

Using google-collections will be much easier for me, if the files are
uploaded to the maven repository.

Original issue reported on code.google.com by [email protected] on 30 Oct 2007 at 9:33

Establish serialized form for all collections

We'll need to establish this and commit to it before 1.0.

We've punted it thus far; most collections just use default serialization
right now, even though this is dumb in some cases like BiMap.

Original issue reported on code.google.com by [email protected] on 1 Nov 2007 at 8:14

Iterators wants filter(Iterable, Predicate)

I immediately ran into a use-case where I wanted to create a filtered
iterator on a list. In other words, rather than

Iterator<Foo> it = Iterables.filter(myList, myPredicate).iterator();
or
Iterator<Foo> it = Iterators.filter(myList.iterator(), myPredicate);

I thought it would be nice to

Iterator<Foo> it = Iterators.filter(myList, myPredicate);


Original issue reported on code.google.com by [email protected] on 12 Oct 2007 at 8:59

iterator with pre-defined cycles count

  /**
   * Returns an iterator that cycles {@code cycleCount} times over the
   * elements of {@code iterable} or until it is empty, that to occur first. 
   * <b>Warning:</b> If {@code cycleCount} has a negative value the resulting
   * iterator may produce an infinite loop. You should use an explicit
break, or
   * be certain that you will eventually remove all the elements.
   */
  public static <T> Iterator<T> cycle(final int cycleCount,
       final Iterable<T> iterable) {
    checkNotNull(iterable);
    return new Iterator<T>() {
      int cycles = cycleCount;
      Iterator<T> iterator = Iterators.emptyIterator();
      Iterator<T> removeFrom;

      public boolean hasNext() {
        if (!iterator.hasNext() && cycles-- != 0) {
          iterator = iterable.iterator();
        }
        return iterator.hasNext();
      }
      public T next() {
        if (!hasNext()) {
          throw new NoSuchElementException();
        }
        removeFrom = iterator;
        return iterator.next();
      }
      public void remove() {
        checkState(removeFrom != null,
            "no calls to next() since last call to remove()");
        removeFrom.remove();
        removeFrom = null;
      }
    };
  }

Original issue reported on code.google.com by [email protected] on 23 Oct 2007 at 6:54

functional iterable

Hi,

Last weekend I thought:
"Why not to use functional programming with Java? More precisely using
Google Collections!"
...

Minutes later... Voila!!!
I can to write pieces of code as:

names.select(new Regexp(".*e$")).transform(new GetLength()).select(new 
OddNumber())

I wanted to move this code to a fluent interface. Now, I dont need the
verbose syntax of the static methods, and, mainly, this code is more easy
to read.

The attached jar file contains the full source code with:
- FunctionalIterable interface, with all methods documented
- StandartFunctionalIterable class, the default implementation
- StandartFunctionalIterableTest class, the show case class


About Fluente Interface:
http://martinfowler.com/bliki/FluentInterface.html
http://en.wikipedia.org/wiki/Fluent_interface

Original issue reported on code.google.com by [email protected] on 22 Oct 2007 at 5:12

Attachments:

Upgrade to Java 6, maintaining Java 5 backport branch

We will upgrade to requiring Java 6, but will create a Java 5-compatible
branch and will include both forms in our release.

Based on the changes listed in

http://java.sun.com/javase/6/docs/technotes/guides/collections/changes6.html

we'll have some work to do...

API - 
* Adopt NavigableFoo in place of SortedFoo throughout the API
* Add ForwardingNavigableFoo, ForwardingDeque
* Add factory methods for the new implementations to Lists/Sets/Maps

Impl -
* Add @Override to methods newly eligible for it
* Adopt the new AbstractMap.Simple(Immutable)Entry classes in place of our
custom code wherever possible

probably other stuff I'm not thinking of.

Original issue reported on code.google.com by [email protected] on 1 Nov 2007 at 8:12

Usage of Functions.compose function

What steps will reproduce the problem?

        HashMap<Object,String> hashMap=new HashMap<Object,String>
();
        hashMap.put("name","prashant");

        HashMap<Object,Object> hashMap1=new HashMap<Object,Object>
();
        hashMap.put("name","prashant");

        Function<Object,Object> hashFuc=Functions.forMap(hashMap1);
        Object o=hashFuc.apply("name");
        System.out.println(o.getClass().getSimpleName());

        Function<Object,String> hashFuc1=Functions.forMap(hashMap);

        Function<Object,String> composeFunc=Functions.compose
(hashFuc,hashFuc1);


What is the expected output? What do you see instead?
Want no compilation problems.

What version of the product are you using? On what operating system?
version which is in beta release.

Please provide any additional information below.
This surely is not an issue with google collections but thought of asking 
for help.As also logged a message in developer mailing list for reference.


Original issue reported on code.google.com by [email protected] on 26 Oct 2007 at 4:15

Deploy 2 jars instead of 1

Currently, 1 jar with:
com.google.common.base
com.google.common.collect

I was hoping you would release a seperate jar for the "base" funtionality, 
which is not related to collections. I'm positive that the base 
functionality will grow as some sort of "commons lang".

Original issue reported on code.google.com by [email protected] on 13 Sep 2007 at 10:14

change Multimap.asMap to return Map<K,? extends Collection<V>>

What steps will reproduce the problem?
N/A

What is the expected output? What do you see instead?
N/A

What version of the product are you using? On what operating system?
0.5 (ALPHA) 

Please provide any additional information below.
The Multimap.asMap method currently returns Map<K,Collection<V>>, which
restricts the return types of the ListMultimap and SetMultimap.  By
changing the return type to Map<K,? extends Collection<V>>, you would allow
the sub-interfaces to return more appropriate types (i.e. ListMultimap
could return Map<K,? extends List<V>>).

Original issue reported on code.google.com by [email protected] on 22 Oct 2007 at 2:57

com.google.common.base.Join suggestions

I quickly skimmed through the Javadoc, and have some suggestions that go 
with the Join class that I wanted to discuss:

* Perhaps rename it "Joins". Join.join sounds like possible a Star Wars 
character. If you don't use import static, that is.

* Use Builder (syntax to be discussed):
  Joins.join("a","b","c").with(":");
  Joins.flushJoin("a","b","c").with(":").to(myAppender);

Great work, guys. I will be enjoying this library.

Original issue reported on code.google.com by [email protected] on 13 Sep 2007 at 10:09

Add @NonNullable annotation

The @Nullable annotation is a good way of positively identifying that a
parameter may be null. The converse may in fact be more useful - specifying
that a parameter *may not* be null.

Aside from adding to the documentary benefit that @Nullable provides,
@NonNullable could be used to actively check the precondition that the
parameter it marks is non-null, using AOP. This would be a neat way of
checking this precondition, without having to directly run the
Preconditions#checkNotNull(T) check as the first line of the method.

Original issue reported on code.google.com by [email protected] on 27 Feb 2008 at 2:11

Creating immutable sorted sets from already-ordered data

Occasionally you have a List of elements which you already know to be in
sorted order. The canonical example is the results from a SQL query with an
ORDER BY clause.

You know the data to be sorted, yet you have no way to offer the niceties
of the SortedSet/NavigableSet APIs to your callers. In order to construct a
TreeSet/etc., you must re-engineer the appropriate comparator that can be
used to sort the data -- but the data is already sorted!

I believe the way out of this is a method Sets.immutablePreSortedSet(List).
 This method would copy the elements out of the list, assuming that
whatever order they come out in is the order you want.  It would not demand
a comparator from you (although, if you can provide one, perhaps it should
accept it, as this could speed up some of the operations.  and if you don't
provide one, what should the set's comparator() return?  Should it return a
Comparators.givenOrder()?).

This idea is not fully-formed, but it's a shame to see methods forced to
use List to model data which is often known to be dup-free and is ordered,
not indexed.

Original issue reported on code.google.com by [email protected] on 23 Oct 2007 at 4:22

Appendable Join.join(Appendable appendable, String delimiter, ... )

Hi,

Since the Javadoc of the method says it returns "The same appendable instance 
that was passed 
in", I was wondering why the signature for the join methods was not something 
like:

public static <T extends Appendable> T join(T appendable, String delimiter, ...)

This signature ensures that the return type will be of the same type than the 
parameter.
This means that if I use a StringBuffer as input, I will get a StringBuffer as 
return value and not an 
Appendable (that need to be casted to StringBuffer :( ).

What do you think about that?

Original issue reported on code.google.com by [email protected] on 27 Oct 2007 at 10:50

provide a fill method similar to Collections.fill() that uses a Supplier

 Collections.fill() allows a List to be populated with a single instance, but there are times where 
you'd want to fill with separate instances.  My usecase was pre-initializing a 
matrix 
(ArrayList<ArrayList<T>>).

something like <T> void fill(List<? super T> list, Supplier<? extends
T> objSupplier) would be great.

Original issue reported on code.google.com by [email protected] on 14 Nov 2007 at 4:51

Typo in Javadoc for interface com.google.common.base.Predicate

The interface-level Javadoc for the interface Predicate contains the
following note. The second occurrence of the word "function" actually reads
"fuction":

"NOTE: This interface could technically extend Function, since a predicate
is just a special case of a fuction (one that returns a boolean)."

Original issue reported on code.google.com by [email protected] on 20 Sep 2007 at 11:00

Support removal from Iterables and Maps based on Predicate

I'd like to be able to filter Iterables and Maps in place. Perhaps adding a
method to Iterables with the following signature:

public static <T> void filterInPlace(
      final Iterable<T> unfiltered, final Predicate<? super T> predicate)

and one to Maps with the following signature:

public static <K, V> void filterInPlace(
      Map<K, V> unfiltered, Predicate<? super K> predicate)

I've attached diffs against the 20071022 snapshot, if you feel this is
worth adding. If not, then it'll stay in my own toolbox of
things-built-on-top-of-google-collections. I've also attached a couple of
simple unit tests.


Original issue reported on code.google.com by [email protected] on 19 Dec 2007 at 4:21

Attachments:

Possible Tuple library contribution

Attached is a possible contribution of a tuple library. The library is
consistent with the collections library and is easy to use, e.g.:

<E0,E1> T2<E1,E0> swap(E0 e0, E1 e1) { return t(e1, e0); }

Note generics and ease of construction.

The files are licensed under LGPL; other licences are probably possible, if
necessary (I own the copyright but need to check with my university that an
alternate licence is OK).

Original issue reported on code.google.com by [email protected] on 4 Dec 2007 at 7:36

Attachments:

Standardize how to create instances of our collections.

It's a bit of a mess out there right now.

All our concrete collection implementation classes should contain their own
static creation methods, rather than having them lumped into classes like
Lists and Sets.  (Lists and Sets would continue to contain creation methods
only for JDK collection types; I'll file a separate issue to discuss those.)

For each of our implementation classes:

I propose that we keep constructors to a minimum, possibly having any
constructors besides the parameterless one being private.  Then I propose
that we have the following static creation methods:

1. newInstance() with no parameters - create an empty instance
2. newInstance(Iterable<? extends E>) (or Map, etc. for other non-Iterable
types) - the "copy constructor"
3. newInstance(....) accepting sizing parameters such as expectedSize, if
applicable
4. newInstanceBackedWith(...) which accepts a backing collection instance,
if applicable

We will NOT have:

* newInstance(Iterator) (use Iterables.addAll())
* newInstance(E[]) or newInstance(E...) (use Arrays.asList() or
Collections.addAll())
* Any combinations of 1-4 above (e.g., initial data plus *also* sizing
parameters or backing collection).

Note that it is important to name #4 above differently from the rest
because we have several implementations that both implement Map and are
backed with a Map.

I also propose that our interfaces provide some documentation that
encourages all implementations to follow these conventions.

Feedback?

Original issue reported on code.google.com by [email protected] on 31 Oct 2007 at 6:18

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.