net.dongliu.commons.lang.collection.Lists Maven / Gradle / Ivy
package net.dongliu.commons.lang.collection;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* utils method for list
*
* @author Dong Liu
*/
public class Lists {
/**
* get a list backend by Array.
*
* {@code List list = Lists.of("test", "test2");}
*
*/
@SafeVarargs
public static List of(T... values) {
return Arrays.asList(values);
}
/**
* get immutable list
*
*
* {@code List list = Lists.immutable("test", "test2");}
*
*/
@SafeVarargs
public static List immutable(T... values) {
return Collections.unmodifiableList(of(values));
}
/**
* get immutable list
*/
public static List immutable(List list) {
return Collections.unmodifiableList(list);
}
/**
* get sub list by begin(included) and end(not included) index.
* begin and end can be negative, will be eval as list.size() + begin/end.
* {@code
* List list = Lists.of(1, 5, 9, 10);
* Lists.sub(list, 1, 3) returns Lists.of(5, 9);
* Lists.sub(list, 1, -1) returns Lists.of(5, 9);
* }
*
*
* @param list can be null. when list is null, always return null
* @return sub list
* @throws ArrayIndexOutOfBoundsException
*/
public static List sub(List list, int begin, int end) {
if (list == null) {
return null;
}
int len = list.size();
if (begin < 0) {
begin += len;
}
if (end < 0) {
end += len;
}
if (begin >= len || begin < 0) {
throw new ArrayIndexOutOfBoundsException("invalid start index:" + begin);
}
if (end > len || end < 0) {
throw new ArrayIndexOutOfBoundsException("invalid end index:" + end);
}
return list.subList(begin, end);
}
/**
* get sub list by begin(included) index, till the end of list.
* begin can be negative, will be eval as list.size() + begin.
* {@code
* List list = Lists.of(1, 5, 9, 10);
* Lists.sub(list, 1) --> Lists.of(5, 9, 10);
* Lists.sub(list, -1) --> Lists.of(10);
* }
*
*
* @param list can be null. when list is null, always return null
* @return subString
* @throws ArrayIndexOutOfBoundsException
*/
public static List sub(List list, int begin) {
return sub(list, begin, list.size());
}
/**
* get sub list from beginning, till the index end(not included).
* end can be negative, will be eval as list.size() + end.
* {@code
* List list = Lists.of(1, 5, 9, 10);
* Lists.rSub(list, 1) --> Lists.of(5);
* Lists.rSub(list, -1) --> Lists.of(1, 5, 9);
* }
*
*
* @param list can be null. when list is null, always return null
* @return subString
* @throws ArrayIndexOutOfBoundsException
*/
public static List rSub(List list, int end) {
return sub(list, 0, end);
}
}