Gizmo5012
Gizmo5012

Reputation: 9

Searching through arraylist based on first character and then printing it out

I can't figure out how to scan through the arraylist and then take "Bravo" and Print it for the letter "B" on my keyboard.

I have tried too many codes

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

public class map {


    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Put in a word, the machine will then translate it to airport codes!");
        String name = in.next();
        List <String> list = new ArrayList<String>();  
        list.add("Alpha"); 
        list.add("Bravo"); 
        list.add("Charlie"); 
        list.add("Delta"); 
        list.add("Foxtrot"); 
        list.add("Echo"); 

        List <String> listClone = new ArrayList<String>(); 
        for (String string : list) {
            if(string.matches("(?i)(A).*")){
                listClone.add(string);
            }
            else if(string.matches("(B).*")){
                listClone.add(string);
            }
        }
     System.out.println(listClone);
}
}

Upvotes: 1

Views: 157

Answers (3)

cutiko
cutiko

Reputation: 10517

You need a map

Map<Character, String> map = new HashMap<>();

map.put('a', "Alpha");
...
//get the user input

for (char c: input.toCharArray()) {
    if (map.containsKey(c)) {
         println(map.get(c));
    }
}

Upvotes: 0

WJS
WJS

Reputation: 40034

If you're just looking for the first character, it would be best to do the following as it avoids unnecessary overhead.

    List <String> listClone = new ArrayList<String>(); 
    for (String string : list) {
        if(string.charAt(0) == 'B') {
            listClone.add(string);
        }
    }

Upvotes: 0

Ryuzaki L
Ryuzaki L

Reputation: 40048

You can use String.startsWith to find word starting with alphabet

 List <String> listClone = new ArrayList<String>(); 
    for (String string : list) {
        if(string.startsWith("B"){
            listClone.add(string);
        }

    }

From java 8 you can use stream

List<String> res = list.stream()
                       .filter(str->str.startWiths("B"))
                       .collect(Collectors.toList());

Upvotes: 2

Related Questions