Java在arraylist中打印姓氏

时间:2015-03-20 18:13:53

标签: java arraylist printing

我有这个

ArrayList<String> players = new ArrayList<String>();

players.add("Albert Pujols");
players.add("Jim Edmonds");
players.add("Josh Hamilton");
players.add("Mike Trout");
players.add("Adrian Gonzalez");
players.add("Price Fielder");
players.add("Steven Strasburg");
players.add("Jose Bautista");
players.add("Bryce Harper");
players.add("Mike Trout");

我如何制作一个只打印姓氏的方法:

Pujols
Edmonds
Hamilton
Trout
Gonzalez
Fielder
Strasburg
Bautista

我有类似的东西,但我卡住了:

public static void printLastName(ArrayList<String> players) {
    for (int i = 0; i < players.size(); i++)
        System.out.println(players.get(i));
}

5 个答案:

答案 0 :(得分:3)

我猜,所有名字都是单个空格分隔的。所以,只需拆分并打印最后一部分

System.out.println(players.get(i).split(" ")[1]);

正如Alexis C所提到的,您应该使用firstName和lastName创建一个模型类,并将类实例存储在List

答案 1 :(得分:1)

你可以介绍一个Player类......

    public class Player {

        final String firstName;
        final String lastName;

        public Player(final String firstName, final String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        @Override
        public String toString() {
            return this.lastName;
        }

        @Override
        public boolean equals(final Object o) {
            if (this == o) {
                 return true;
            }
            if (!(o instanceof Player)) {
                return false;
            }

            final Player player = (Player) o;

            if (firstName != null ? !firstName.equals(player.firstName) : player.firstName != null) {
                return false;
            }
            return !(lastName != null ? !lastName.equals(player.lastName) : player.lastName != null);    
        }

        @Override
        public int hashCode() {
            int result = firstName != null ? firstName.hashCode() : 0;
            result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
            return result;
        }     
    }

答案 2 :(得分:0)

您应该将代码更改为

public static void printLastName(ArrayList<String> players) {
for (int i = 0; i < players.size(); i++)
    System.out.println(players.get(i).split(" ")[1]);
}

答案 3 :(得分:0)

使用Stringsplit()函数\\s的空格分开,因为“”在java中不起作用

这是示例

 String lastname = players.get(i).Split("\\s+")[1]; //even split("\\s"); will also work

如果您想使用Pattern class使用以下代码

private static final Pattern SPACE = Pattern.compile(" ");//outside for loop
String lastname = SPACE.split(players.get(i))[1]; // inside for loop

答案 4 :(得分:0)

你可能想让Arraylist持有一个String数组,例如

ArrayList<String[]> players = new ArrayList<String[]>();
String[] player1 = {"Albert", "Pujols"};
players.add(player1);
System.out.println(players.get(0)[1]);