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

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

    }


哈士奇WWW
浏览 181回答 2
2回答

元芳怎么了

如果要将元素存储到数组中,可以List先将其放入List数组中,然后通过List.toArray以下方式将其转换为数组:LinkedList<String> linkedList = new LinkedList<>();for (String res : listOne) {&nbsp; &nbsp; if (res.startsWith("a") || res.startsWith("g")) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("--> " + res);&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("** " + res);&nbsp; &nbsp; &nbsp; &nbsp; linkedList.add(res);&nbsp; &nbsp; }}String[] result1 = new String[linkedList.size()];linkedList.toArray(result1);

米脂

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 {&nbsp; &nbsp; public static void main(String[] args) {&nbsp; &nbsp; &nbsp; &nbsp; // TODO Auto-generated method stub&nbsp; &nbsp; &nbsp; &nbsp; display();&nbsp; &nbsp; }&nbsp; &nbsp; public static void display() {&nbsp; &nbsp; &nbsp; &nbsp; String[] inpArray = { "apple", "orange", "grapes" };&nbsp; &nbsp; &nbsp; &nbsp; List<String> listOne = new ArrayList<String>(Arrays.asList(inpArray));&nbsp; &nbsp; &nbsp; &nbsp; List<String> listTwo = new ArrayList<String>();&nbsp; &nbsp; &nbsp; &nbsp; listTwo.add("melon");&nbsp; &nbsp; &nbsp; &nbsp; listTwo.add("apple");&nbsp; &nbsp; &nbsp; &nbsp; listTwo.add("mango");&nbsp; &nbsp; &nbsp; &nbsp; String[] result1 = new String[listOne.size()];&nbsp; &nbsp; &nbsp; &nbsp; int i =0;&nbsp; &nbsp; &nbsp; &nbsp; for (String res : listOne) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (res.startsWith("a") || res.startsWith("g")) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("--> " + res);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("** " + res);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result1[i++] = res;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; for(String val : result1){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Value"+val);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java