Get specific ArrayList item

As many have already told you: mainList.get(3); Be sure to check the ArrayList Javadoc. Also, be careful with the arrays indices: in Java, the first element is at index 0. So if you are trying to get the third element, your solution would be mainList.get(2);

Check if a value exists in ArrayList

Just use ArrayList.contains(desiredElement). For example, if you’re looking for the conta1 account from your example, you could use something like: if (lista.contains(conta1)) { System.out.println(“Account found”); } else { System.out.println(“Account not found”); } Edit: Note that in order for this to work, you will need to properly override the equals() and hashCode() methods. If you are … Read more

How can I create an Array of ArrayLists?

As per Oracle Documentation: “You cannot create arrays of parameterized types” Instead, you could do: ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4); As suggested by Tom Hawting – tackline, it is even better to do: List<List<Individual>> group = new ArrayList<List<Individual>>(4);

make arrayList.toArray() return more specific types

Like this: List<String> list = new ArrayList<String>(); String[] a = list.toArray(new String[0]); Before Java6 it was recommended to write: String[] a = list.toArray(new String[list.size()]); because the internal implementation would realloc a properly sized array anyway so you were better doing it upfront. Since Java6 the empty array is preferred, see .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])? … Read more

How to sort an ArrayList in Java [duplicate]

Use a Comparator like this: List<Fruit> fruits= new ArrayList<Fruit>(); Fruit fruit; for(int i = 0; i < 100; i++) { fruit = new Fruit(); fruit.setname(…); fruits.add(fruit); } // Sorting Collections.sort(fruits, new Comparator<Fruit>() { @Override public int compare(Fruit fruit2, Fruit fruit1) { return fruit1.fruitName.compareTo(fruit2.fruitName); } }); Now your fruits list is sorted based on fruitName.

How to declare an ArrayList with values? [duplicate]

In Java 9+ you can do: var x = List.of(“xyz”, “abc”); // ‘var’ works only for local variables Java 8 using Stream: Stream.of(“xyz”, “abc”).collect(Collectors.toList()); And of course, you can create a new object using the constructor that accepts a Collection: List<String> x = new ArrayList<>(Arrays.asList(“xyz”, “abc”)); Tip: The docs contains very useful information that usually … Read more