All Questions
10,748
questions
1297
votes
25
answers
2.0m
views
Converting array to list in Java
How do I convert an array to a list in Java?
I used the Arrays.asList() but the behavior (and signature) somehow changed from Java SE 1.4.2 (docs now in archive) to 8 and most snippets I found on the ...
1067
votes
33
answers
1.5m
views
How do I join two lists in Java?
Is there a simpler way than:
List<String> newList = new ArrayList<String>();
newList.addAll(listOne);
newList.addAll(listTwo);
Conditions:
Do not modify the original lists.
JDK only.
No ...
913
votes
25
answers
2.6m
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?
811
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?
756
votes
11
answers
1.4m
views
Convert list to array in Java [duplicate]
How can I convert a List to an Array in Java?
Check the code below:
ArrayList<Tienda> tiendas;
List<Tienda> tiendasList;
tiendas = new ArrayList<Tienda>();
Resources res = this....
732
votes
23
answers
588k
views
Java: convert List<String> to a join()d String
JavaScript has Array.join()
js>["Bill","Bob","Steve"].join(" and ")
Bill and Bob and Steve
Does Java have anything like this? I know I can cobble something ...
635
votes
15
answers
469k
views
Type List vs type ArrayList in Java [duplicate]
(1) List<?> myList = new ArrayList<?>();
(2) ArrayList<?> myList = new ArrayList<?>();
I understand that with (1), implementations of the List interface can be swapped. It ...
621
votes
17
answers
646k
views
Why do I get an UnsupportedOperationException when trying to remove an element from a List?
I have this code:
public static String SelectRandomFromTemplate(String template,int count) {
String[] split = template.split("|");
List<String> list=Arrays.asList(split);
Random r = ...
611
votes
15
answers
1.1m
views
Convert Set to List without creating new List
I am using this code to convert a Set to a List:
Map<String, List<String>> mainMap = new HashMap<>();
for (int i=0; i < something.size(); i++) {
Set<String> set = getSet(...
581
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?
525
votes
13
answers
1.9m
views
How to initialize List<String> object in Java?
I can not initialize a List as in the following code:
List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
...
514
votes
26
answers
685k
views
What is the difference between Set and List?
What is the fundamental difference between the Set<E> and List<E> interfaces?
464
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);
...
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?
403
votes
32
answers
347k
views
Array or List in Java. Which is faster?
I have to keep thousands of strings in memory to be accessed serially in Java. Should I store them in an array or should I use some kind of List ?
Since arrays keep all the data in a contiguous chunk ...
400
votes
10
answers
497k
views
How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it? [duplicate]
I'm trying to remove some elements from an ArrayList while iterating it like this:
for (String str : myArrayList) {
if (someCondition) {
myArrayList.remove(str);
}
}
Of course, I get ...
387
votes
7
answers
460k
views
Is there a concurrent List in Java's JDK?
How can I create a concurrent List instance, where I can access elements by index? Does the JDK have any classes or factory methods I can use?
349
votes
11
answers
653k
views
How to convert a Collection to List?
I am using TreeBidiMap from the Apache Collections library. I want to sort this on the values which are doubles.
My method is to retrieve a Collection of the values using:
Collection coll = themap....
314
votes
25
answers
1.4m
views
How to print out all the elements of a List in Java?
I am trying to print out all the elements of a List, however it is printing the pointer of the Object rather than the value.
This is my printing code...
for(int i=0;i<list.size();i++){
System....
311
votes
20
answers
354k
views
How do you cast a List of supertypes to a List of subtypes?
For example, lets say you have two classes:
public class TestA {}
public class TestB extends TestA{}
I have a method that returns a List<TestA> and I would like to cast all the objects in that ...
300
votes
20
answers
627k
views
How to convert List to Map?
Recently I have conversation with a colleague about what would be the optimal way to convert List to Map in Java and if there any specific benefits of doing so.
I want to know optimal conversion ...
299
votes
9
answers
203k
views
Java List.add() UnsupportedOperationException
I try to add objects to a List<String> instance but it throws an UnsupportedOperationException.
Does anyone know why?
My Java code:
String[] membersArray = request.getParameterValues('members')...
297
votes
5
answers
162k
views
What is the difference between List.of and Arrays.asList?
Java 9 introduced new factory methods for lists, List.of:
List<String> strings = List.of("first", "second");
What's the difference between the previous and the new option? That is, what's the ...
294
votes
14
answers
622k
views
Java List.contains(Object with field value equal to x)
I want to check whether a List contains an object that has a field with a certain value. Now, I could use a loop to go through and check, but I was curious if there was anything more code efficient.
...
289
votes
12
answers
337k
views
Convert Iterator to List
Given Iterator<Element>, how can we conveniently convert that Iterator to a List<Element>, so that we can use List's operations on it such as get(index), add(element), etc.
268
votes
9
answers
203k
views
How to randomize two ArrayLists in the same fashion?
I have two arraylist filelist and imgList which related to each other, e.g. "H1.txt" related to "e1.jpg". How to automatically randomized the list of imgList according to the randomization of fileList?...
248
votes
21
answers
715k
views
HashMap with multiple values under the same key
Is it possible to implement a HashMap with one key and two values?
Just as HashMap<userId, clientID,timeStamp>?
If not, is there any other way to implement the storage of multiple values e.g. ...
248
votes
19
answers
209k
views
Why doesn't java.util.Set have get(int index)?
Why does the java.util.Set interface lack get(int Index), or any similar get() method?
It seems that sets are great for putting things into, but I can't find an elegant way of retrieving a single item ...
247
votes
12
answers
330k
views
How to get a reversed list view on a list in Java?
I want to have a reversed list view on a list (in a similar way than List#sublist provides a sublist view on a list). Is there some function which provides this functionality?
I don't want to make ...
234
votes
31
answers
346k
views
How can I reverse a Java 8 stream and generate a decrementing IntStream of values?
General question: What's the proper way to reverse a stream? Assuming that we don't know what type of elements that stream consists of, what's the generic way to reverse any stream?
Specific question:...
225
votes
16
answers
562k
views
How can I sort a List alphabetically?
I have a List<String> object that contains country names. How can I sort this list alphabetically?
213
votes
6
answers
229k
views
Most concise way to convert a Set<T> to a List<T>
For example, I am currently doing this:
Set<String> setOfTopicAuthors = ....
List<String> list = Arrays.asList(
setOfTopicAuthors.toArray( new String[0] ) );
Can you beat this ?
194
votes
19
answers
356k
views
Best way to concatenate List of String objects? [duplicate]
What is the best way to concatenate a list of String objects? I am thinking of doing this way:
List<String> sList = new ArrayList<String>();
// add elements
if (sList != null)
{
...
187
votes
3
answers
404k
views
Best way to convert list to comma separated string in java [duplicate]
I have Set<String> result & would like to convert it to comma separated string. My approach would be as shown below, but looking for other opinion as well.
List<String> slist = new ...
184
votes
13
answers
295k
views
How to convert a List<String> into a comma separated string without iterating List explicitly [duplicate]
List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
Now i want an output from this list as 1,2,3,4 without explicitly iterating over it.
181
votes
10
answers
270k
views
Why am I not getting a java.util.ConcurrentModificationException in this example?
Note: I am aware of the Iterator#remove() method.
In the following code sample, I don't understand why the List.remove in main method throws ConcurrentModificationException, but not in the remove ...
179
votes
15
answers
716k
views
stale element reference: element is not attached to the page document
I have list which has multiple links under each section. Each section has same links I need to click a particular link under each section. I have written the below code but when it executes it gives ...
175
votes
11
answers
332k
views
Check if one list contains element from the other
I have two lists with different objects in them.
List<Object1> list1;
List<Object2> list2;
I want to check if element from list1 exists in list2, based on specific attribute (Object1 and ...
169
votes
10
answers
471k
views
Sorting a list with stream.sorted() in Java
I'm interested in sorting a list from a stream. This is the code I'm using:
list.stream()
.sorted((o1, o2)->o1.getItem().getValue().compareTo(o2.getItem().getValue()))
.collect(Collectors....
169
votes
12
answers
179k
views
How can I access a folder inside of a resource folder from inside my jar File?
I have a resources folder/package in the root of my project, I "don't" want to load a certain File. If I wanted to load a certain File, I would use class.getResourceAsStream and I would be ...
168
votes
1
answer
301k
views
What is the difference between List and ArrayList? [duplicate]
I've been using ArrayList recently in my android project at the office and I'm a bit confused between List and ArrayList, what is the difference of the two and what should I use?
Also I saw some ...
167
votes
24
answers
368k
views
Intersection and union of ArrayLists in Java
Are there any methods to do so? I was looking but couldn't find any.
Another question: I need these methods so I can filter files.
Some are AND filters and some are OR filters (like in set theory), ...
165
votes
8
answers
145k
views
Polymorphism: Why use "List list = new ArrayList" instead of "ArrayList list = new ArrayList"? [duplicate]
Possible Duplicate:
Why should the interface for a Java class be prefered?
When should I use
List<Object> list = new ArrayList<Object>();
ArrayList inherits from List, so if some ...
164
votes
13
answers
349k
views
Group a list of objects by an attribute
I need to group a list of objects (Student) using an attribute (Location) of the particular object. The code is like below:
public class Grouping {
public static void main(String[] args) {
...
164
votes
10
answers
166k
views
Get last element of Stream/List in a one-liner
How can I get the last element of a stream or list in the following code?
Where data.careas is a List<CArea>:
CArea first = data.careas.stream()
.filter(c -> c.bbox....
156
votes
8
answers
502k
views
Does java.util.List.isEmpty() check if the list itself is null? [duplicate]
Does java.util.List.isEmpty() check if the list itself is null, or do I have to do this check myself?
For example:
List<String> test = null;
if (!test.isEmpty()) {
for (String o : test) {
...
152
votes
18
answers
284k
views
How to copy Java Collections list
I have an ArrayList and I want to copy it exactly. I use utility classes when possible on the assumption that someone spent some time making it correct. So naturally, I end up with the Collections ...
147
votes
4
answers
127k
views
Difference between Iterator and Listiterator?
Iterator ite = Set.iterator();
Iterator ite = List.iterator();
ListIterator listite = List.listIterator();
We can use Iterator to traverse a Set or a List or a Map. But ListIterator can only be used ...
143
votes
6
answers
257k
views
"Instantiating" a List in Java? [duplicate]
Trying to use the following code:
List<Integer> list = new List<Integer>();
I get the following error message:
java.util.List is abstract; cannot be instantiated
What does this mean ...
137
votes
13
answers
230k
views
Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))
What is the difference between
List<Integer> list1 = new ArrayList<Integer>(Arrays.asList(ia)); // Copy
List<Integer> list2 = Arrays.asList(ia);
, where ia is an array of ...