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);
* Lists.sub(list, 1, 100) returns Lists.of(5, 9, 10);
* Lists.sub(list, -100, 100) returns Lists.of(1, 5, 9, 10);
* Lists.sub(list, 5, 0) returns empty list;
* Lists.sub(null, 5, 0) returns null;
* }
*
*
* @param list can be null. when list is null, always return null
* @return sub list
*/
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;
}
begin = Math.max(begin, 0);
begin = Math.min(begin, len);
end = Math.max(begin, end);
end = Math.min(end, len);
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);
* Lists.sub(list, -100) --> Lists.of(1, 5, 9, 10);
* Lists.sub(null, -2) returns null;
* }
*
*
* @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());
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy