I have a class SomeClass
with a static member myMap
enter code here
that has the form HasmMap<String,ArrayList<SomeOtherClass>>
which gets de-serialized from a file.
I have a method
public ArrayList<SomeOtherClass> getList(final String key, final int N)
that is supposed to lookup key
in the map and return the first N
elements of the corresponding ArrayList
, or the whole thing if the list has <= N
elements. How should I implement the TODO
line below:
public ArrayList<SomeOtherClass> getList(final String key, final int N)
{
ArrayList<SomeOtherClass> arr = myMap.get(key);
if (arr == null) return null;
if (arr.size() <= N)
{
return arr;
}
else
{
// TODO: return first N elements
}
}
to do it efficiently, i.e. without creating unneeded copies in memory while actually returning the right data?
The subList() method of java. util. ArrayList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.)
Java 8. We can split a list based on some size or based on a condition.
Example: Java ArrayList.subList Method In the following example the subList() method is used to get a portion of this list between the specified fromIndex, inclusive, and toIndex. ArrayList new_color_list1 = new ArrayList (color_list. subList(1, 8));
We can return an array in Java from a method in Java. Here we have a method createArray() from which we create an array dynamically by taking values from the user and return the created array.
Create a sublist with List
s subList
method.
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.
Start at index 0 (inclusive start index), and end at index N
(exclusive end index).
return arr.subList(0, N);
This does not copy the items to a new list; it returns a list view over the existing list.
return arr.subList(0, N);
The documentation is your friend.
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#subList(int,%20int)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With