Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly return part of ArrayList in Java?

I have a class SomeClass with a static member myMap enter code herethat 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?

like image 783
I Z Avatar asked Jan 11 '16 21:01

I Z


People also ask

How do you retrieve a portion of an ArrayList?

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.)

Can we split ArrayList in Java?

Java 8. We can split a list based on some size or based on a condition.

How do you create a subset of a list in Java?

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));

Can you return an ArrayList from a method in Java?

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.


2 Answers

Create a sublist with Lists 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.

like image 162
rgettman Avatar answered Oct 18 '22 09:10

rgettman


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)

like image 24
Jacob Young Avatar answered Oct 18 '22 07:10

Jacob Young