这段代码可以以另一种方式写成吗?

huangapple go评论66阅读模式
英文:

what would this code be in an alternative way

问题

私人列表<Passenger> getPassengersToRelease() {

    返回 passengerList.stream()
            .筛选(用户 -&gt; 用户.getDestinationFloor() == currentFloor)
            .收集(Collectors.toList());
}
英文:

would anyone be able to write this code in an easier way to understand

 private List&lt;Passenger&gt; getPassengersToRelease() {

        return passengerList.stream()
                .filter(user -&gt; user.getDestinationFloor() == currentFloor)
                .collect(Collectors.toList());
    }

I really cant get my head around it and have been struggling on it for a few days. Thanks

答案1

得分: 5

以下是一个粗略的翻译,使用了老式的循环方式:

private List<Passenger> getPassengersToRelease() {
    List<Passenger> result = new ArrayList<>();
    for (Passenger p : passengerList()) {
        if (p.getDestinationFloor() == currentFloor) {
            result.add(p);
        }
    }
    return result;
}

但更好理解基于流的解决方案是将其分解:

// 将乘客转化为流
passengerList.stream()

    // 从流中移除目标楼层不符合条件的乘客
    .filter(user -> user.getDestinationFloor() == currentFloor)

    // 将剩余的乘客收集到一个新列表中
    .collect(Collectors.toList);

唯一棘手的一步是 filter(...) 步骤。传递给 filter 的内容是一个 lambda 表达式。基本上,它是一个内联(无名)函数,将从 Passenger 映射到 boolean 值。user 是该函数的输入变量,表达式 user.getDestinationFloor() == currentFloor 的值是其输出。

因此,过滤器的工作方式如下。对于流中的每个 Passenger,调用 lambda 表达式。这将为您提供 truefalse。如果获得 true,则保留该 Passenger。如果获得 false,则将其从流中删除;即被“过滤掉”。

英文:

Here is a rough translation into an old-fashioned loop:

private List&lt;Passenger&gt; getPassengersToRelease() {
    List&lt;Passenger&gt; result = new ArrayList&lt;&gt;();
    for (Passenger p: passengerList()) {
        if (p.getDestinationFloor() == currentFloor) {
             result.add(p);
        }
    }
    return result;
}

But a better way to understand the stream-based solution is doing is to break it down:

// give us the passengers as a stream
passengerList.stream() 

   // remove any passengers from the stream that DO NOT have the given
   // destination floor.
   .filter(user -&gt; user.getDestinationFloor() == currentFloor)

   // put the passengers that remain into a new list.
   .collect(Collectors.toList);

The only tricky step is the filter(...) step. The stuff passed as a parameter to filter is a lambda expression. Basically, it is an inline (unnamed) function that maps from a Passenger to a boolean value. The user is the function's input variable, and the value of the expression user.getDestinationFloor() == currentFloor is its output.

So the filter works like this. For each Passenger in the stream, you call the lambda expression. This gives you either true or false. If you get true you pass on the Passenger. If you get false you drop it from the stream; i.e. it is "filtered out".

答案2

得分: 2

这里,我认为这是重构你上面发布的代码的最简单方法。如果我错了,请纠正我。

private List<Passenger> getPassengersToRelease() {

    List<Passenger> newPassengerList = new ArrayList<>();
    for(Passenger user : passengerList) {
        if(user.getDestinationFloor() == currentFloor) {
            newPassengerList.add(user);
        }
    }
    return newPassengerList;
}
英文:

Here, I think this is the simplest way to refactor code you posted above. If I'm wrong, please correct me.

private List&lt;Passenger&gt; getPassengersToRelease() {

        List&lt;Passenger&gt; newPassengerList = new ArrayList&lt;&gt;();
        for(Passenger user : passengerList) {
            if(user.getDestinationFloor() == currentFloor) {
                newPassengerList.add(user);
            }
        }
        return newPassengerList;
    }

答案3

得分: 1

这段代码利用了自Java 8以来可用的Stream API

简而言之,您的代码遍历了一个Passenger对象的List,并且.filter(user -&gt; user.getDestinationFloor() == currentFloor)只过滤具有与currentFloor值相等的destinationFloor字段的Passenger对象。在过滤之后,将结果收集到一个List中并返回。

英文:

This piece of code is levereging the Stream api available since Java 8.

In short, your code goes through a List of Passenger objects, and .filter(user -&gt; user.getDestinationFloor() == currentFloor) only filters Passenger objects that have the destinationFloor field equal with currentFloor value. After the filtering, the results are collected into a List and returned.

答案4

得分: 1

private List<Passenger> getPassengersToRelease() 
{
    List<Passenger> floorPassengers;
    for (Passenger user : passengerList)
    {
        if (user.getDestinationFloor() == currentFloor)
        {
            floorPassengers.add(user);
        }
    }
    return floorPassengers;
}

应该检查语法,我手头没有编译器。但基本上这个调用会被翻译成带有条件的 for-each 循环。


<details>
<summary>英文:</summary>

This:

private List<Passenger> getPassengersToRelease()
{
List floorPassengers;
for( Passenger user : passengerList )
{
if( user.getDestinationFloor() == currentFloor )
{
floorPassengers.add( user );
}
}
return floorPassengers;
}

Should check the syntax, I have no compiler at hand. But basically the call translates to a for each with a condition.

</details>



# 答案5
**得分**: 1

你可以将其改写为

```java
private List<Passenger> getPassengersToRelease() {
    List<Passenger> list = new ArrayList<Passenger>();

    for (Passenger passenger : passengerList) {
        if (passenger.getDestinationFloor() == currentFloor) {
            list.add(passenger);
        }
    }
    return list;
}
我还建议您阅读[Java SE 8 Streams][1]。
英文:

You can rewrite it as

private List&lt;Passenger&gt; getPassengersToRelease() {
	List&lt;Passenger&gt; list = new ArrayList&lt;Passenger&gt;();

	for(Passenger passenger : passengerList){
		if(passenger.getDestinationFloor() == currentFloor){
			list.add(passenger);
		}
	}
    return list;
}

I also recommend you go through Java SE 8 Streams.

huangapple
  • 本文由 发表于 2020年4月6日 18:10:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/61057387.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定