How to Make a New List in Java

How to make a new List in Java

List myList = new ArrayList();

or with generics (Java 7 or later)

List<MyType> myList = new ArrayList<>();

or with generics (Old java versions)

List<MyType> myList = new ArrayList<MyType>();

How to initialize ListString object in Java?

If you check the API for List you'll notice it says:

Interface List<E>

Being an interface means it cannot be instantiated (no new List() is possible).

If you check that link, you'll find some classes that implement List:

All Known Implementing Classes:

AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, Vector

Some of those can be instantiated (the ones that are not defined as abstract class). Use their links to know more about them, I.E: to know which fits better your needs.

The 3 most commonly used ones probably are:

 List<String> supplierNames1 = new ArrayList<String>();
List<String> supplierNames2 = new LinkedList<String>();
List<String> supplierNames3 = new Vector<String>();

Bonus:

You can also instantiate it with values, in an easier way, using the Arrays class, as follows:

List<String> supplierNames = Arrays.asList("sup1", "sup2", "sup3");
System.out.println(supplierNames.get(1));

But note you are not allowed to add more elements to that list, as it's fixed-size.

Create a new list with values from fields from existing list

You can using Java 8 with lambda expressions :

List<String> listNames = people.stream().map(u -> u.getName()).collect(Collectors.toList());


import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Test {
public static void main(String args[]){
List<Person> people = Arrays.asList(new Person("Bob",25,"Geneva"),new Person("Alice",27,"Paris"));
List<String> listNames = people.stream().map(u -> u.getName()).collect(Collectors.toList());
System.out.println(listNames);
}
}
class Person
{
private String name;
private int age;
private String location;

public Person(String name, int age, String location){
this.name = name;
this.age = age;
this.location = location;
}

public String getName(){
return this.name;
}

}

Output :

[Bob, Alice]

Demo here.



Alternatively, you can define a method that will take your list as parameter and the function you want to apply for each element of this list :

public static <X, Y> List<Y> processElements(Iterable<X> source, Function <X, Y> mapper) {
List<Y> l = new ArrayList<>();
for (X p : source)
l.add(mapper.apply(p));
return l;
}

Then just do :

List<String> lNames = processElements(people, p -> p.getName()); //for the names
List<Integer> lAges = processElements(people, p -> p.getAge()); //for the ages
//etc.

If you want to group people by age, the Collectors class provide nice utilities (example):

Map<Integer, List<Person>> byAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));

How to create a new list and add a value in single statement

I love one-liners as much as anyone else, but they come with a cost - namely they're harder to read than being explicit. So lets start with the "normal" way to do what you're describing:

ArrayList<E> copy = new ArrayList<>(list);
copy.add(value);
return copy;

It's a few lines, but it's efficient, straight-forward, and easy to read. We want any alternative to be an improvement on this syntax, not simply replacing readability for conciseness. If you're trying to decide between the implementation you've posted and the "normal" version, the "normal" version should win hands down.


We can try to improve on your solution with Stream.concat() and Stream.of().

return Stream.concat(list.stream(), Stream.of(value))
.collect(Collectors.toList());

It's technically all one statement now, but we still need to split it over multiple lines to make it readable. It's also a lot more boilerplate than the standard implementation.


Instead we can use the builder pattern Guava provides for its Immutable collections:

return new ImmutableList.Builder<E>().addAll(list).add(value).build();

This is more concise, and conveys our intent nicely. This is how I would recommend implementing the behavior you describe (using Guava or by defining your own builder pattern). Not only does it work for this specific use case, but it scales to any arbitrary combination of values and collections.


I think (it's hard to read :) ) your example actually replaces the last value of the list with your new value, rather than adding it to the end. If that's what you want, just use List.sublist() to truncate the last element from the list, e.g.:

list.sublist(0, list.size() - 1)

Use that anywhere I have list above to exclude the last value.

How to make a new list with a property of an object which is in another list

Java 8 way of doing it:-

List<Integer> idList = students.stream().map(Student::getId).collect(Collectors.toList());

How to Create and Initialize (in Java) a ListString[] in the same statement? (Editors please NOTE: this *not* the same as just a ListString)

The correct answer was given in the comments (above) by @user16320675 , and this works well. It handles both the creation of the outer List and the internal array of strings. Other answers pointing to a simple Array asList are for simple strings, which is not the question that was asked.

to create a mutable list

final List<String[]> rolesCsv =
new ArrayList<String[]>Collections.singletonList(new String[]{"Role Name","Description"}));

Otherwise (despite the array, its element, will not be immutable)

final List<String[]> rolesCsv =
Collections.singletonList(new String[]{"Role Name","Description"})

How to quickly and conveniently create a one element arraylist

Fixed size List

The easiest way, that I know of, is to create a fixed-size single element List with Arrays.asList(T...) like

// Returns a List backed by a varargs T.
return Arrays.asList(s);

Variable size List

If it needs vary in size you can construct an ArrayList and the fixed-sizeList like

return new ArrayList<String>(Arrays.asList(s));

and (in Java 7+) you can use the diamond operator <> to make it

return new ArrayList<>(Arrays.asList(s));

Single Element List

Collections can return a list with a single element with list being immutable:

Collections.singletonList(s)

The benefit here is IDEs code analysis doesn't warn about single element asList(..) calls.

How to make a new list with a property of an Map which is in another list

List<String> names = list.stream()
.map(i -> i.get("name").toString())
.collect(Collectors.toList());

Since i.get("name").toString() might produce a NPE, it's smart to filter out maps that don't contain the key "name":

List<String> names = list.stream()
.filter(i -> i.containsKey("name"))
.map(i -> i.get("name").toString())
.collect(Collectors.toList());

or

List<String> names = list.stream()
.map(i -> i.get("name"))
.filter(Objects::nonNull)
.map(Object::toString)
.collect(Collectors.toList());

Initial size for the ArrayList

You're confusing the size of the array list with its capacity:

  • the size is the number of elements in the list;
  • the capacity is how many elements the list can potentially accommodate without reallocating its internal structures.

When you call new ArrayList<Integer>(10), you are setting the list's initial capacity, not its size. In other words, when constructed in this manner, the array list starts its life empty.

One way to add ten elements to the array list is by using a loop:

for (int i = 0; i < 10; i++) {
arr.add(0);
}

Having done this, you can now modify elements at indices 0..9.



Related Topics



Leave a reply



Submit