Array Lists in java - java

Is there a way to remove all empty cells in an ArrayList by just a built in function call? I saw trimToSize but I didn't really get what it meant.
For example, suppose I have an array that contains {1,2,3}. Lets say I say array.remove(1) so now the array looks like {1,null,3}. Is there a function to call to make it converge to be {1,3}?
I know I can hard code a method to do that for me but I was just curious.

That's exactly what remove does.
Removes the element at the specified
position in this list. Shifts any
subsequent elements to the left
(subtracts one from their indices).
Now, if you're talking about arrays, not ArrayList, the answer is no.

If you are using an ArrayList, you don't need to worry about compacting the array after removing an element from it. The ArrayList class takes care of this kind of housekeeping.
If you are using an array, you could use the Commons Lang ArrayUtils class. The removeElement methods in this class simplify removing an element from an array and shifting all elements after it to the left.

In here you find a post that shows how to remove all null elements in a Collection
List<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(2);
myList.add(null);
myList.add(3);
myList.add(null);
myList.add(4);
System.out.println("With null values");
for(Integer i: myList)
System.out.println(i);
myList.removeAll(Collections.singleton(null));
System.out.println("After deleting null values");
for(Integer i: myList)
System.out.println(i);
Output:
With null values
1
2
null
3
null
4
After deleting null values
1
2
3
4

Related

Getting IndexOutOfBoundsException in ArrayList while using .add(index, element)

I am using the list.add(index, element) function to insert elements into an ArrayList, where the index is not in order.
For eg,
first i call list.add(5, element5)
and then list.add(3, element3)
I am getting the exception java.lang.IndexOutOfBoundsException: Invalid index 5, size is 0 exception.
Please tell where I am doing wrong and how can I fix this.
You cannot add elements to indexes which do not yet exist. In general, as Japhei said, you can only add elements to indexes smaller or equal to the array length. This means, if your ArrayList is still empty, you can only add elements at index 0 or without specifying the index (which will just add it to the end).
What you want to do is initialize your ArrayList with empty elements. I normally use meaningless values like 0 or -1 for integers or empty strings depending on the array type (or null elements), and just fill them later.
But if you know how many elements you have, or what array size you need, why not just use a normal array? That would be the right way to do it.
The problem is that your ArrayList is empty and therefore the insert (via add(int index, E element) fails.
Consider using the add(E element) (documentation) to add the element to the end of the list.
You can only use indexes that are existing or one larger than the last existing. Otherwise you would have some spots with no element in it.
If you need a ficxed length to store elements on a specified position, try to fill the List before with empty entries or use an array:
MyElement[] myArray = new MyElement[theLengthOfMyArray];
myArray[5] = elementXY;
Or fill a List with null elements (shown here):
List<MyElement> myList = new ArrayList<>();
for (int i = 0; i < theTargetLengthOfMyList; i++) {
myList.add(null);
}
myList.set(5, elementXY);
So what is probably happening is, that you defined a size for your list on creating said list. According to your error message this would be 0. And on a list with the size 0, you can't set the 5th or 3rd position to anything, as they don't exist. If you would add the line where you define the variable "list", we could help you further!
You can't add to index not in list range:
IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())
See java doc:
https://docs.oracle.com/javase/8/docs/api/java/util/List.html#add-int-E-

In an array of arraylists, get the largest arraylist

I have an array with multiple arraylists of different sizes.
I want to find the index of the largest arraylist in the array. I tried this:
Collections.max(disc);
disc being the name of the array of arraylists.
ArrayList I believe doesn't implement the Comparable interface so I can't do it like this. Is there a way to make a custom comparable for sizes of ArrayLists?
If you want to know the index of the largest sub-ArrayList then you're basically looking for an information relative to where the largest ArrayList is stored. This research is not based solely on the intrinsic characteristics of your biggest ArrayList but also on where it is located.
Using Collections.max won't help you, even if you redefine its natural ordering providing a new Comparator, because you would only get the largest ArrayList not the index where it is stored. If you want to find the index you have to manually loop the outer ArrayList and whenever you find a new largest sub-ArrayList save its index.
Of course, all of what I said is based on the sole condition that you're interested in retrieving the index and not the biggest sub-ArrayList itself. If you're simply looking for the biggest sub-ArrayList then Collections.max with a Comparator implementation is what you need.
You can't add interfaces to an existing class. If you want ArrayList to implement Comparable, you'll need to write an adaptor class that contains an ArrayList and implements the interface.
But, in your case, you don't need that. Comparable has a sister interface called Comparator which is an external object specifying how to compare some type. It can be used to provide alternative sorting mechanisms (descending rather than ascending, for instance) or, as in your case, to add comparison capabilities to an existing class that lacks them. And Collections.max has an overload that takes a comparator.
Collections.max(disc, (a, b) -> a.size() - b.size())
Note that if you're on a really old Java version, you'll need to explicitly create a Comparator instance, rather than using SAM conversion like I do above.
I want to find the index of the largest arraylist in the array.
Collections.max does not take an array nor does it return an index. It returns the large element in a Collection.
Without knowing your exact data structure I am using a list of lists.
List<List<Integer>> ss =
List.of(
List.of(1, 2, 3),
List.of(1, 2, 3, 4),
List.of(1, 2)
);
This just compares the sizes and returns the index that targets the maximum list
int maxIndex = IntStream.range(0, ss.size()).boxed().collect(Collectors
.maxBy(Comparator.comparing(i -> ss.get(i).size()))).get();
prints
1
The maxBy Collector returns an Optional of which I immediately took the value. You may want to assign it to an Optional and then process appropriately for an empty collection.
A simpler way of doing it is with a loop. Just find the max size and associate the index with it.
maxIndex = 0;
int maxSize = 0;
for (int i = 0; i < ss.size(); i++) {
int size = ss.get(i).size();
if (size> maxSize) {
maxIndex = i;
maxSize = size;
}
}
System.out.println(maxIndex);
prints
1
I prefer the more clever solution by WJS, but here is another solution as well. This one here is not as brief but might be easier to comprehend on first reading.
You said:
I have an array with multiple arraylists of different sizes. I want to find the index of the largest arraylist in the array.
As they discussed, Collections.max returns you a reference to the largest object, not the the index of that object within the array.
So we need two steps:
Determine the largest element.
Get the index of that largest object.
First, some example data.
List[] arrayOfListsOfIntegers =
List.of(
List.of( 1 ) ,
List.of( 1001 , 1002 , 1003 , 1004 ) ,
List.of( 101 , 102 , 103 ) ,
List.of( 11 , 12 )
)
.toArray( List[] :: new );
Determine the largest element
Use Arrays.asList to make a view onto that array that appears as a List. This way we can call convenient List methods.
Then make a stream of that list. Sort the elements of the stream by getting each one’s size. Make a new list from the sorted elements. We know the last element of that sorted list has the biggest element.
List sorted =
Arrays
.asList( arrayOfListsOfIntegers )
.stream()
.sorted( Comparator.comparingInt( List :: size ) )
.toList();
Get a reference to that biggest element, the last element of our sorted list of lists.
Object target = sorted.get( sorted.size() - 1 );
Get the index of that largest object
That target object is what we want to locate within our original list. We can locate by calling List#indexOf. Here again we use Arrays.asList to mask our array as a List.
int index = Arrays.asList( arrayOfListsOfIntegers ).indexOf( target );

How can I just get the last record in the java.util.List using subList() or any other method?

Say I have a list of elements whose size is 100. Now I only want the 100th record in the list and the rest of all records from 1-99 should be removed from the list.
I have tried the below piece of code but no change in list size as I see it.
//Output list.size() returns 100
list.subList(list.size()-1, list.size());
//Output list.size() returns 100 after subList() called...
How can I get just the last record in the java.util.List using subList() or using any other methods available in Java?
list.subList returns a new List backed by the original List.
You need to store the returned list in a variable in order to use it:
List<String> subList = list.subList(list.size()-1, list.size());
subList.size() will be 1. list will remain unchanged.
If you want to remove all but the last element from the original List, you can write:
list.subList(0, list.size()-1).clear();
Now the original List will contain just 1 element.
ArrayList.subList method returns a sublist of your list without modifying your existing list.
So you need to do;
list = list.subList(list.size()-1, list.size());
To get just last record without changing list you could use:
element = list.get(list.size()-1);
this will work for any list, most effective for ArrayList implementation.
You can do it by importing com.google.common.collect.Iterables, but be aware if list is empty it will throw NoSuchElementException.
public MODEL getLastEntry(List<MODEL> list) {
return Iterables.getLast(list);
}
You can also use stream for it: https://www.baeldung.com/java-stream-last-element

How to delete one value from, and decrease the length of, a String array

I don't understand how to decrease the length of a String array. For example, with this code:
String[][] array = new String[5][2];
array[1][0] = "what";
array[2][0] = "is";
.....
.....
array[5][0] = "?";
How can I delete array[5][0] and get array.length to be 4, not 5?
If you want to remove the array element from the end , you can also use Arrays.copyOf() since jdk 1.6+
For example:
array = Arrays.copyOf(array, 4);
It just copy the original array 's first 4 elements to a new array , so it have the same effect as deleting the array[5]
If you want to remove an element from an specified index , you can use ArrayUtils.remove() from Apache Commons Lang 3 to do it .
/**Remove the element at index 3**/
array =ArrayUtils.remove(array, 3);
You cannot delete an item from an array.
But you can create a new array with smaller size and copy the content of the old array to the new one. Then, assign the value of the reference to the new array.
Consider using java.util.List. It has a method remove().
Using arrays for such things is very time consuming. I can suggest these solutions:
1. Use one of the data structures provided by Java libraries. I'd go with HashMap since its structure allows mapping a value to a key (HashMap ) and it does the part of adding, finding and removing items. You can also use them for multi-level hashmaps if you need more than 2 columns (HashMap ) you can look that up.
2. Use a List or ArrayList structure. Make a list that contains arrays or a special structure you create to store your data.
3. (Not recommended) Go for the manual route. If you have a fixed-length array, you can shift the rows back to remove that row, and use an index to define the last row. If you have a dynamic-length array you'll need to reconstruct it each time you remove a row.

What is the best way to remove the first element from an array?

I have string array (String[]) and I need to remove the first item. How can I do that efficiently?
The size of arrays in Java cannot be changed. So, technically you cannot remove any elements from the array.
One way to simulate removing an element from the array is to create a new, smaller array, and then copy all of the elements from the original array into the new, smaller array.
String[] yourArray = Arrays.copyOfRange(oldArr, 1, oldArr.length);
However, I would not suggest the above method. You should really be using a List<String>. Lists allow you to add and remove items from any index. That would look similar to the following:
List<String> list = new ArrayList<String>(); // or LinkedList<String>();
list.add("Stuff");
// add lots of stuff
list.remove(0); // removes the first item
Simplest way is probably as follows - you basically need to construct a new array that is one element smaller, then copy the elements you want to keep to the right positions.
int n=oldArray.length-1;
String[] newArray=new String[n];
System.arraycopy(oldArray,1,newArray,0,n);
Note that if you find yourself doing this kind of operation frequently, it could be a sign that you should actually be using a different kind of data structure, e.g. a linked list. Constructing a new array every time is an O(n) operation, which could get expensive if your array is large. A linked list would give you O(1) removal of the first element.
An alternative idea is not to remove the first item at all, but just increment an integer that points to the first index that is in use. Users of the array will need to take this offset into account, but this can be an efficient approach. The Java String class actually uses this method internally when creating substrings.
You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:
Shift every element up one, then set the last element to null.
Create a new array, then copy it.
You can use System.arraycopy for either of these. Both of these are O(n), since they copy all but 1 element.
If you will be removing the first element often, consider using LinkedList instead. You can use LinkedList.remove, which is from the Queue interface, for convenience. With LinkedList, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator to that position. However, accessing an arbitrary element by index is O(n).
Keep an index of the first "live" element of the array. Removing (pretending to remove) the first element then becomes an O(1) time complexity operation.
To sum up, the quick linkedlist method:
List<String> llist = new LinkedList<String>(Arrays.asList(oldArray));
llist.remove(0);
An alternative ugly method:
String[] a ={"BLAH00001","DIK-11","DIK-2","MAN5"};
String[] k=Arrays.toString(a).split(", ",2)[1].split("]")[0].split(", ");

Categories