比较两个列表与Java-8

问题描述 投票:-1回答:1

我想比较两个列表(eastList和westList)。 EastList将包含值0westList将包含值1。返回值应为5。代码是正确的。我可以用流写第二个for循环吗?如何编写使用Java 8功能摘录的代码以获得高效代码?请帮忙。谢谢...

import java.util.*;

public class Solution {

public int solution(int[] A) {
    List<Integer> eastList = new ArrayList<>();
    List<Integer> westList = new ArrayList<>();
    int count = 0;

    for(int i = 0; i < A.length; i++) {
        if(A[i] == 0) {
            eastList.add(i);
        }
        else {
            westList.add(i);
        }
    }

    for(int m = 0; m < eastList.size(); m++) {
        for(int n = 0; n < westList.size(); n++) {
            if(eastList.get(m) < westList.get(n)) {
                count++;
            }
        }
    }
    return count;
}

public static void main(String[] args) {
    Solution solution = new Solution();
    int[] A = {0,1,0,1,1};    
    solution.solution(A);
}
}
java
1个回答
0
投票

对于Java9及更高版本,您可以使用dropWhile

eastList.stream().map(
  east -> westList.stream().dropWhile(west -> west <= east).count()
).sum()

而且(在我看来)基于流的代码更具表现力,因为dropWhilecount调用准确地描述了我们对eastwestList的处理方式>

更新:根据拉胡尔的评论进行修正

© www.soinside.com 2019 - 2024. All rights reserved.