假设我有一个这样的列表:
[a, b, c, d, e, f, PASS, g, h]
但是我希望只要出现"PASS"
一词,就用剩余的数据列出另一个列表。
赞:
[[a, b, c, d, e, f], [g, h]]
答案 0 :(得分:1)
这可以写为通用方法(我已经在我的stackoverflow答案中有了它,所以我想我之前已经读过它了……我将尝试找到具体位置):
getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT
答案 1 :(得分:0)
这是一种使用循环在分隔符上“拆分” Comparable
列表的方法:
private static <T extends Comparable<T>> List<List<T>> split(
List<T> original, T delimiter) {
List<List<T>> res = new ArrayList<>();
List<T> current = new ArrayList<>();
for (T f : original) {
if (f.compareTo(delimiter) == 0) {
res.add(current);
current = new ArrayList<>();
continue;
}
current.add(f);
}
if (!current.isEmpty()) {
res.add(current);
}
return res;
}
使用以下命令进行测试时,它返回[[a, b, c, d, e, f], [g, h]]
:
public static void main(String[] args) throws Exception {
List<String> list =
Arrays.asList("a", "b", "c", "d", "e", "f", "PASS", "g", "h");
System.out.println(split(list, "PASS"));
}
答案 2 :(得分:0)
另一种解决方案
public static void main(String[] args) {
String[] ar = { "a", "b", "c", "d", "e", "f", "PASS", "g", "h" };
ArrayList<String> al = new ArrayList<String>(Arrays.asList(ar));
ArrayList<String> al1 = new ArrayList<String>(al.subList(0, al.indexOf("PASS")));
ArrayList<String> al2 = new ArrayList<String>(al.subList(al.indexOf("PASS") + 1, al.size()));
ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
listOLists.add(al1);
listOLists.add(al2);
}
答案 3 :(得分:0)
您可以先创建一个startIndex和endIndex。跟踪每个索引,当您看到“ PASS”时,只需对列表进行从startIndex到endIndex的子列表。然后,相应地更新索引。
public static List<List<String>> getSplittedList (List<String> li)
{
List<List<String>> lists = new ArrayList<>();
int startIndex = 0;
int endIndex = 0;
for(int i = 0; i < li.size(); i++)
{
if(li.get(i).equals("PASS"))
{
if(startIndex < endIndex)
lists.add(li.subList(startIndex, endIndex));
startIndex = i+1;
endIndex = i+1;
}
else
endIndex++;
}
if(startIndex < li.size())
lists.add(li.subList(startIndex, li.size()));
return lists;
}
答案 4 :(得分:0)
我安排了一个简单的解决方案,请检查此匹配项是否适合您。谢谢。
/**
* @author Duminda Hettiarachchi
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StringSubList {
ArrayList<String> subList;
public StringSubList() {
subList = new ArrayList<String>();
}
public void subList(List<String> list) {
int passIndex = list.indexOf("PASS");
List<String> list1 = (List<String>) list.subList(0, passIndex);
List<String> list2 = (List<String>) list.subList(passIndex+1, list.size());
List<List<String>> subLists = new ArrayList<List<String>>();
subLists.add(list1);
subLists.add(list2);
System.out.println("List 1 :" + subLists.get(0));
System.out.println("List 2 : " + subLists.get(1));
}
public static void main(String[] args) {
String mainArr[] = {"a", "b", "c", "d", "e", "f", "PASS", "g", "h"};
List<String> myList = Arrays.asList("a", "b", "c", "d", "e", "f", "PASS", "g", "h");
new StringSubList().subList(myList); `enter code here`
}
}
输出:
列表1:[a,b,c,d,e,f]
列表2:[g,h]