我有两个列表。其中显示了一组人中每个人对某个游戏的成功尝试次数。
public class SuccessfulAttempts{
String name;
int successCount;
}
List<SuccessfulAttempts> success;
以及每个人的总尝试次数。
public class TotalAttempts{
String name;
int totalCount;
}
List<TotalAttempts> total;
我想显示小组中每个人的成功百分比。
public class PercentageSuccess{
String name;
float percentage;
}
List<PercentageSuccess> percentage;
假设我已经像这样填充了前两个列表。
success.add(new SuccessfulAttempts(Alice, 4));
success.add(new SuccessfulAttempts(Bob, 7));
total.add(new TotalAttempts(Alice, 5));
total.add(new TotalAttempts(Bob, 10));
现在我想计算每个人使用 Java Streams 的成功百分比。所以我实际上需要列表的这种结果 List<PercentageSuccess> percentage
.
new PercentageSuccess(Alice, 80);
new PercentageSuccess(Bob, 70);
我想并行计算它们(爱丽丝的百分比和鲍勃的百分比)(我知道如何使用循环按顺序进行)。我如何使用 Java Streams(或任何其他简单的方法)实现这一点??
最佳答案
我建议将您的其中一个列表转换为 map ,以便更轻松地访问计数。否则,对于一个列表的每个值,您必须在另一个列表中循环,这将是 O(n^2) 复杂性。
List<SuccessfulAttempts> success = new ArrayList<>();
List<TotalAttempts> total = new ArrayList<>();
success.add(new SuccessfulAttempts("Alice", 4));
success.add(new SuccessfulAttempts("Bob", 7));
total.add(new TotalAttempts("Alice", 5));
total.add(new TotalAttempts("Bob", 10));
// First create a Map
Map<String, Integer> attemptsMap = success.parallelStream()
.collect(Collectors.toMap(SuccessfulAttempts::getName, SuccessfulAttempts::getSuccessCount));
// Loop through the list of players and calculate percentage.
List<PercentageSuccess> percentage =
total.parallelStream()
// Remove players who have not participated from List 'total'. ('attempt' refers to single element in List 'total').
.filter(attempt -> attemptsMap.containsKey(attempt.getName()))
// Calculate percentage and create the required object
.map(attempt -> new PercentageSuccess(attempt.getName(),
((attemptsMap.get(attempt.getName()) * 100) / attempt.getTotalCount())))
// Collect it back to list
.collect(Collectors.toList());
percentage.forEach(System.out::println);
关于java - 与 Java Streams 并行循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41563542/