例如我有列表、类和方法:
List<Client> myClient = new ArrayList<>();
public class Client {
String firstName;
String lastName;
String cID;
boolean subscription = false;
}
public String activateSubscription(String customerID){
for( Client myCustomer: myClient ){
if( myCustomer.cID == customerID ){
myCustomer.setSubscription();
break;
}
}
return null;
}
public void getClientName(String customerID){
String nameCustomer = null;
for( Client myCustomer: myClient ){
if( myClient.clientID == customerID ){
nameCustomer = myCustomer.getFullName();
break;
}
}
return nameCustomer;
}
public int getNumberOfSubsrtipion(){
int count = 0;
for( Client myCustomer: myClient ){
if( myCustomer.getSubscription ){
count += 1;
}
}
return count;
}
我是 Java 新手,我想知道是否可以简化这段代码?
也许有更简单的方法来统计订阅客户并通过 ID 搜索客户?
使用
Streams
你可以简化它是的
public long getNumberOfSubscription() {
return myClient.stream().filter(Client::getSubscription).count();
}
public void activateSubscription(String customerID) {
myClient.stream().filter(c -> c.getcID().equals(customerID))
.findFirst()
.ifPresent(client -> client.setSubscription(true));
}
public String getClientName(String customerID) {
try {
return myClient.stream().filter(c -> c.getcID().equals(customerID))
.findFirst()
.orElseThrow().getFullName();
} catch (Exception e) {
return null;
}
}