leftso 1478 0 2018-08-03 14:48:41

文章位置:左搜> 编程技术> 正文
首先,数据结构。这只是一个简单的橄榄球运动员,有名字和评级。
class RugbyPlayer {
    private String name;
    private Integer rating;
    
    RugbyPlayer(String name, Integer rating) {
        this.name = name;
        this.rating = rating;
    }

    public String toString() {
        return name + "," + rating;
    }
        
    public String getName() {
        return name;
    }
        
    public Integer getRating() {
        return rating;
    }
}

//...
//...
List<RugbyPlayer> players = Arrays.asList(
    new RugbyPlayer("Tadgh Furlong", 9),
    new RugbyPlayer("Bundee AKi", 7),
    new RugbyPlayer("Rory Best", 8),
    new RugbyPlayer("Jacob StockDale", 8)
);

查找特定记录

// Find Tadgh Furlong
Optional<RugbyPlayer> result = players.stream()
    .filter(player -> player.getName().indexOf("Tadgh")  >= 0)
    .findFirst();      
String outputMessage = result.isPresent() ? result.get().toString() : "not found";
System.out.println(outputMessage);

查找具体记录

// Find all players with a rating over 8
List<RugbyPlayer> ratedPlayers = players.stream()
    .filter(player -> player.getRating() >= 8)
    .collect(Collectors.toList());
ratedPlayers.forEach(System.out::println);

从对象类型映射到另一个

// Map the Rugby players to just names. 
// Note, the way we convert the list to a stream and then back again to a to a list using the collect API. 
System.out.println("Names only...");
List<String> playerNames = players.stream().map(player -> player.getName()).collect(Collectors.toList());
playerNames.forEach(System.out::println);

执行减少计算

System.out.println("Max player rating only...");
Optional<Integer> maxRatingOptional = players.stream().map(RugbyPlayer::getRating).reduce(Integer::max);
String maxRating = maxRatingOptional.isPresent() ? maxRatingOptional.get().toString() : "No max";
System.out.println("Max rating=" + maxRating);
 
编程技术