如何在Java中存储列表中匹配的元素

时间:2018-06-23 09:58:48

标签: java arrays string list

how to convert ascii value of 49 to actual char in java

我的代码在下面,我正在尝试存储不是以前缀a或g开头的列表中的元素

 void display(){
    String[] inpArray={"apple","orange","grapes"};
    LinkedList<String> listOne = new LinkedList<String>(Arrays.asList(inpArray));
    LinkedList<String> listTwo = new LinkedList<String>();
    listTwo.add("melon");
    listTwo.add("apple");
    listTwo.add("mango");
    String[] result1 = {};
    for(String res : listOne){

    if(res.startsWith("a")||res.startsWith("g")){
        System.out.println("--> "+res);
    }else{
        System.out.println("** "+res);
        //result1 = res;//unable to store in string array or to list
        // here i have to add all strings how to do that please help me
    }

2 个答案:

答案 0 :(得分:1)

Please find the code for storing the element in String array using index i;

package com.test.stackoverflow;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestClass {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        display();
    }

    public static void display() {
        String[] inpArray = { "apple", "orange", "grapes" };
        List<String> listOne = new ArrayList<String>(Arrays.asList(inpArray));
        List<String> listTwo = new ArrayList<String>();
        listTwo.add("melon");
        listTwo.add("apple");
        listTwo.add("mango");
        String[] result1 = new String[listOne.size()];
        int i =0;
        for (String res : listOne) {

            if (res.startsWith("a") || res.startsWith("g")) {
                System.out.println("--> " + res);
            } else {
                System.out.println("** " + res);
                result1[i++] = res;
            }
        }

        for(String val : result1){
            System.out.println("Value"+val);
        }
    }

}

答案 1 :(得分:0)

如果要将元素存储到数组中,可以先将它们放入List中,然后通过ListList.toArray转换为数组:

LinkedList<String> linkedList = new LinkedList<>();
for (String res : listOne) {
    if (res.startsWith("a") || res.startsWith("g")) {
        System.out.println("--> " + res);
    } else {
        System.out.println("** " + res);
        linkedList.add(res);
    }
}
String[] result1 = new String[linkedList.size()];
linkedList.toArray(result1);