小编Man*_*gos的帖子

如何使用Java 8 Stream API转换代码?

我正在编写一种简单的方法来打印一系列游戏结果的统计数据。每个游戏都有一个结果列表,其中包含根据游戏结果列出的枚举。我的老师在我的代码中注释了一个TODO:

public static void printStatistics(List<Game> games) {
    float win = 0;
    float lose = 0;
    float draw = 0;
    float all = 0;

    //TODO: should be implemented /w stream API
    for (Game g : games) {
        for (Outcome o : g.getOutcomes()) {
            if (o.equals(Outcome.WIN)) {
                win++;
                all++;
            } else if (o.equals(Outcome.LOSE)) {
                lose++;
                all++;
            } else {
                draw++;
                all++;
            }
        }
    }
    DecimalFormat statFormat = new DecimalFormat("##.##");

    System.out.println("Statistics: The team won: " + statFormat.format(win * 100 / all) + " …
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

3
推荐指数
1
解决办法
81
查看次数

我可以将类的字段传递给构造函数或方法吗?

我有以下课程:

public abstract class Map {
    protected PriorityQueue<Node> openNodes;
}
Run Code Online (Sandbox Code Playgroud)

我的实现目前是这样工作的:

public Map() {
        PriorityQueue<Node> openNodes = new PriorityQueue<Node>((Node node1, Node node2) -> Integer.compare(node1.getFinalCost(), node2.getFinalCost()));
    }
Run Code Online (Sandbox Code Playgroud)

但是,我也想使用这样的实现:

public Map() {
        PriorityQueue<Node> openNodes = new PriorityQueue<Node>((Node node1, Node node2) -> Integer.compare(node1.getHeuristicCost(), node2.getHeuristicCost()));
    }
Run Code Online (Sandbox Code Playgroud)

有没有办法将我的 Node 类的heuristicCostfinalCost字段传递给构造函数以实现这些不同的行为?像这样的东西:

public Map(*fieldName*) {
        PriorityQueue<Node> openNodes = new PriorityQueue<Node>((Node node1, Node node2) -> Integer.compare(node1.get*fieldName*(), node2.get*fieldName*()));
    }
Run Code Online (Sandbox Code Playgroud)

如果没有,您能否提出解决方案来实现这一目标?

java oop structure

1
推荐指数
1
解决办法
42
查看次数

标签 统计

java ×2

java-8 ×1

java-stream ×1

oop ×1

structure ×1