Questions tagged [collections]
Collections APIs provide developers with a set of classes and interfaces that make it easier to handle collections of objects.
24,103
questions
4319
votes
35
answers
1.7m
views
What are the differences between a HashMap and a Hashtable in Java?
What are the differences between a HashMap and a Hashtable in Java?
Which is more efficient for non-threaded applications?
3984
votes
46
answers
3.4m
views
How do I efficiently iterate over each entry in a Java Map?
If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?
Will the ordering of ...
3614
votes
34
answers
1.4m
views
When to use LinkedList over ArrayList in Java?
I've always been one to simply use:
List<String> names = new ArrayList<>();
I use the interface as the type name for portability, so that when I ask questions such as this, I can rework ...
3347
votes
35
answers
3.8m
views
Initialization of an ArrayList in one line
I wanted to create a list of options for testing purposes. At first, I did this:
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
...
1886
votes
65
answers
1.8m
views
Sort a Map<Key, Value> by values
I need to sort a Map<Key, Value> on the values.
Since the values are not unique, I find myself converting the keySet into an array, and sorting that array through array sort with a custom ...
1631
votes
22
answers
1.9m
views
How to directly initialize a HashMap (in a literal way)?
Is there some way of initializing a Java HashMap like this?:
Map<String,String> test =
new HashMap<String, String>{"test":"test","test":"test"};
What would be the correct syntax? I ...
1301
votes
31
answers
523k
views
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
We all know you can't do the following because of ConcurrentModificationException:
for (Object i : l) {
if (condition(i)) {
l.remove(i);
}
}
But this apparently works sometimes, but ...
1280
votes
17
answers
954k
views
Converting 'ArrayList<String> to 'String[]' in Java
How might I convert an ArrayList<String> object to a String[] array in Java?
1247
votes
43
answers
1.0m
views
How can I initialise a static Map?
How would you initialise a static Map in Java?
Method one: static initialiser
Method two: instance initialiser (anonymous subclass)
or
some other method?
What are the pros and cons of each?
Here ...
1052
votes
13
answers
362k
views
Difference between <? super T> and <? extends T> in Java [duplicate]
What is the difference between List<? super T> and List<? extends T> ?
I used to use List<? extends T>, but it does not allow me to add elements to it list.add(e), whereas the List&...
937
votes
25
answers
1.1m
views
How to initialize HashSet values by construction?
I need to create a Set with initial values.
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
Is there a way to do this in one line of code? For instance, it's useful for a ...
914
votes
25
answers
2.7m
views
How to make a new List in Java
We create a Set as:
Set myset = new HashSet()
How do we create a List in Java?
911
votes
15
answers
152k
views
Efficiency of Java "Double Brace Initialization"?
In Hidden Features of Java the top answer mentions Double Brace Initialization, with a very enticing syntax:
Set<String> flavors = new HashSet<String>() {{
add("vanilla");
add("...
879
votes
10
answers
602k
views
How to convert Set to Array?
Set seems like a nice way to create Arrays with guaranteed unique elements, but it does not expose any good way to get properties, except for generator [Set].values, which is called in an awkward way ...
843
votes
12
answers
695k
views
How can I turn a List of Lists into a List in Java 8?
If I have a List<List<Object>>, how can I turn that into a List<Object> that contains all the objects in the same iteration order by using the features of Java 8?
839
votes
19
answers
791k
views
How to convert an Array to a Set in Java
I would like to convert an array to a Set in Java. There are some obvious ways of doing this (i.e. with a loop) but I would like something a bit neater, something like:
java.util.Arrays.asList(Object[...
813
votes
13
answers
1.1m
views
How do I convert a Map to List in Java?
How do I convert a Map<key,value> to a List<value>? Should I iterate over all map values and insert them into a list?
777
votes
16
answers
799k
views
How can I convert List<Integer> to int[] in Java? [duplicate]
How can I convert a List<Integer> to int[] in Java?
I'm confused because List.toArray() actually returns an Object[], which can be cast to neither Integer[] nor int[].
Right now I'm using a loop ...
773
votes
17
answers
737k
views
Easiest way to convert a List to a Set in Java
What is the easiest way to convert a List to a Set in Java?
771
votes
31
answers
875k
views
How to filter a Java Collection (based on predicate)?
I want to filter a java.util.Collection based on a predicate.
763
votes
20
answers
1.3m
views
How do I remove an array item in TypeScript?
I have an array that I've created in TypeScript and it has a property that I use as a key. If I have that key, how can I remove an item from it?
717
votes
13
answers
1.3m
views
Ways to iterate over a list in Java
Being somewhat new to the Java language I'm trying to familiarize myself with all the ways (or at least the non-pathological ones) that one might iterate through a list (or perhaps other collections) ...
698
votes
11
answers
321k
views
Why there is no ConcurrentHashSet against ConcurrentHashMap
HashSet is based on HashMap.
If we look at HashSet<E> implementation, everything is been managed under HashMap<E,Object>.
<E> is used as a key of HashMap.
And we know that HashMap ...
684
votes
35
answers
582k
views
Java 8 Distinct by property
In Java 8 how can I filter a collection using the Stream API by checking the distinctness of a property of each object?
For example I have a list of Person object and I want to remove people with the ...
660
votes
28
answers
1.3m
views
How to convert comma-separated String to List?
Is there any built-in method in Java which allows us to convert comma separated String to some container (e.g array, List or Vector)? Or do I need to write custom code for that?
String commaSeparated =...
626
votes
15
answers
662k
views
Why is there no SortedList in Java?
In Java there are the SortedSet and SortedMap interfaces. Both belong to the Java Collections framework and provide a sorted way to access the elements.
However, in my understanding there is no ...
625
votes
6
answers
776k
views
Is there a short contains function for lists?
Given a list xs and a value item, how can I check whether xs contains item (i.e., if any of the elements of xs is equal to item)? Is there something like xs.contains(item)?
For performance ...
584
votes
40
answers
1.0m
views
How do I remove repeated elements from ArrayList?
I have an ArrayList<String>, and I want to remove repeated strings from it. How can I do this?
583
votes
21
answers
772k
views
How to convert int[] into List<Integer> in Java?
How do I convert int[] into List<Integer> in Java?
Of course, I'm interested in any other answer than doing it in a loop, item by item. But if there's no other answer, I'll pick that one as the ...
570
votes
7
answers
489k
views
C# Set collection?
Does anyone know if there is a good equivalent to Java's Set collection in C#? I know that you can somewhat mimic a set using a Dictionary or a HashTable by populating but ignoring the values, but ...
552
votes
12
answers
348k
views
HashSet vs. List performance
It's clear that a search performance of the generic HashSet<T> class is higher than of the generic List<T> class. Just compare the hash-based key with the linear approach in the List<T&...
518
votes
28
answers
436k
views
Most efficient way to increment a Map value in Java
I hope this question is not considered too basic for this forum, but we'll see. I'm wondering how to refactor some code for better performance that is getting run a bunch of times.
Say I'm creating a ...
513
votes
47
answers
441k
views
Get nth character of a string in Swift
How can I get the nth character of a string? I tried bracket([]) accessor with no luck.
var string = "Hello, world!"
var firstChar = string[0] // Throws error
ERROR: 'subscript' is unavailable: ...
502
votes
15
answers
448k
views
Retrieving a List from a java.util.stream.Stream in Java 8
I was playing around with Java 8 lambdas to easily filter collections. But I did not find a concise way to retrieve the result as a new list within the same statement. Here is my most concise approach ...
497
votes
6
answers
434k
views
LINQ .Any VS .Exists - What's the difference?
Using LINQ on collections, what is the difference between the following lines of code?
if(!coll.Any(i => i.Value))
and
if(!coll.Exists(i => i.Value))
When I disassemble .Exists, it looks like ...
493
votes
21
answers
420k
views
Easy way to convert Iterable to Collection
In my application I use 3rd party library (Spring Data for MongoDB to be exact).
Methods of this library return Iterable<T>, while the rest of my code expects Collection<T>.
Is there any ...
488
votes
19
answers
158k
views
Is it better to return null or empty collection?
That's kind of a general question (but I'm using C#), what's the best way (best practice), do you return null or empty collection for a method that has a collection as a return type ?
486
votes
7
answers
160k
views
defaultdict of defaultdict?
Is there a way to have a defaultdict(defaultdict(int)) in order to make the following code work?
for x in stuff:
d[x.a][x.b] += x.c_int
d needs to be built ad-hoc, depending on x.a and x.b ...
465
votes
21
answers
1.3m
views
How to sort a List/ArrayList?
I have a List of doubles in java and I want to sort ArrayList in descending order.
Input ArrayList is as below:
List<Double> testList = new ArrayList();
testList.add(0.5);
testList.add(0.2);
...
465
votes
3
answers
138k
views
Is there an AddRange equivalent for a HashSet in C#
With a list you can do:
list.AddRange(otherCollection);
There is no add range method in a HashSet.
What is the best way to add another ICollection to a HashSet?
454
votes
11
answers
63k
views
What are the reasons why Map.get(Object key) is not (fully) generic
What are the reasons behind the decision to not have a fully generic get method
in the interface of java.util.Map<K, V>.
To clarify the question, the signature of the method is
V get(Object ...
438
votes
22
answers
1.0m
views
Getting an element from a Set
Why doesn't Set provide an operation to get an element that equals another element?
Set<Foo> set = ...;
...
Foo foo = new Foo(1, 2, 3);
Foo bar = set.get(foo); // get the Foo element from the ...
434
votes
9
answers
1.1m
views
How to get the first element of the List or Set? [duplicate]
I'd like to know if I can get the first element of a list or set. Which method to use?
424
votes
6
answers
141k
views
Cost of len() function
What is the cost of len() function for Python built-ins? (list/tuple/string/dictionary)
420
votes
11
answers
496k
views
Java - How to create new Entry (key, value)
I'd like to create new item that similarly to Util.Map.Entry that will contain the structure key, value.
The problem is that I can't instantiate a Map.Entry because it's an interface.
Does anyone ...
420
votes
8
answers
449k
views
How to quickly and conveniently create a one element arraylist [duplicate]
Is there a Utility method somewhere that can do this in 1 line? I can't find it anywhere in Collections, or List.
public List<String> stringToOneElementList(String s) {
List<String> ...
409
votes
8
answers
464k
views
How to easily initialize a list of Tuples?
I love tuples. They allow you to quickly group relevant information together without having to write a struct or class for it. This is very useful while refactoring very localized code.
Initializing a ...
396
votes
10
answers
462k
views
Java Ordered Map
Is there an object in Java that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are ...
381
votes
5
answers
199k
views
Difference between a Seq and a List in Scala
I've seen in many examples that sometimes a Seq is being used, while other times is the List...
Is there any difference, other than the former one being a Scala type and the List coming from Java?
378
votes
13
answers
415k
views
What is the Simplest Way to Reverse an ArrayList?
What is the simplest way to reverse this ArrayList?
ArrayList<Integer> aList = new ArrayList<>();
//Add elements to ArrayList object
aList.add("1");
aList.add("2");
aList.add("3");
aList....