我在 android 中做一个项目,我有一个问题我的数组列表值是这样的
[men-1, men-2, men-3, women-1, women-2, women-3]
如何将这些值拆分为不同的数组?即如何保存men-1,men-2,men-3
在一个数组和women-1,women-2,women-3
另一个数组中?
the below code may help you
import java.util.Arrays;
public class Test{
public static void main(String[] args) {
String[] input = new String[] {"men-1", "men-2", "men-3", "women-1", "women-2", "women-3"};
int arr1Size=getCount(input, "women");
String[] arr1 = new String[arr1Size];
String[] arr2 = new String[input.length-arr1Size];
int i=0,j=0;
for(String str: input){
if(str.contains("women")){
arr1[i] = str;
i++;
}else{
arr2[j] = str;
j++;
}
}
System.out.println(Arrays.deepToString(arr1));
System.out.println(Arrays.deepToString(arr2));
}
public static int getCount(String[] input, String find){
int count=0;
for(String str: input){
if(str.contains(find)){
count++;
}
}
return count;
}
}
没有细节很难帮助你,但你可能应该
element.startsWith("man")
instanceof
类似的运算符if (element instanceof Man){listOfMans.add(element)}
toArray(T[] array)
每个List
实例的方法。如果这些是类的对象,那么您可以使用 instanceOf 运算符轻松完成...否则下面的代码可以帮助您..您可以仅使用数组以及使用 arraylist 来完成
/**
*
*/
package com.sharique.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* @author Sharique
*
*/
public class Test {
/**
* @param args
*/
//List<Integer> list = new ArrayList<>();
//int[] arr = new int[10];
//int[] ar1= arr.clone();
public void usingArrays(){
StringBuffer sb1 = new StringBuffer("Men");
String[] arrays = {"Men-1","Men-2","Men-3","Women-1","Women-2","Women-3"};
String[] arrOfMen = new String[3];
String[] arrOfWomen = new String[3];
String str=null;
int count1=0;
int count2=0;
for(int i=0;i<arrays.length;i++){
str=arrays[i];
if(str.contains(sb1)){
arrOfMen[count1++]=str;
}else{
arrOfWomen[count2++]=str;
}
}
for(int i=0;i<arrOfMen.length;i++)
System.out.print(arrOfMen[i]+" ");
//For a new Line
System.out.println();
for(int i=0;i<arrOfWomen.length;i++)
System.out.print(arrOfWomen[i]+" ");
}
public void usingArrayList(){
String[] arrays1 = {"Men-1","Men-2","Men-3","Women-1","Women-2","Women-3"};
List<String> list = new ArrayList<>(Arrays.asList(arrays1));
String[] arrays2 = new String[3];
StringBuffer sb = new StringBuffer("Women");
int count=0;
String str=null;
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
str =iterator.next();
if(str.contains(sb)){
arrays2[count++] = str;
iterator.remove();
}
}
//for a new line
System.out.println();
arrays1 = list.toArray(new String[list.size()]);
for(int i=0;i<arrays1.length;i++)
System.out.print(arrays1[i]+" ");
//for a new line
System.out.println();
for(int i=0;i<arrays2.length;i++)
System.out.print(arrays2[i]+" ");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test = new Test();
test.usingArrays();
test.usingArrayList();
}
}