gpt4 book ai didi

java - 如何计算并仅返回 ArrayList 中为真的对象?

转载 作者:行者123 更新时间:2023-12-01 05:53:27 27 4
gpt4 key购买 nike

我想计算所有为 true 的对象并返回它(正如我在 countNational 中尝试做的那样。我用来将对象分配为 true/false 的方法在不同的类中并命名为 NationalMessage。我粘贴了它在主要方法下面。

public class Ex6 
{
public static int countNational (ArrayList<Message> messageList)
{

int countTrue = 0; //will count those that are true

for (int i = 0; i<= messageList.size(); i++)
{
if(messageList.get(i)==true) //GETTING ERROR SAYING CAN'T COMPARE BOOLEAN
countTrue = countTrue + 1;
}
return countTrue;
}
public static void main(String[] args)
{
ArrayList<Message> messageList = new ArrayList<Message>();
messageList.add(new NationalMessage("UKJohn","UKMark","aa"));
messageList.add(new NationalMessage("UKJohn","FRJean","aa"));
messageList.add(new Message("Mike","John","aa"));
System.out.println(countNational(messageList));
}
}

*************************** 下面是来自一个名为 National Message 的单独类的方法************ **********************

public NationalMessage(String ssender, String rreceiver, String ccontent)
{
super(ssender,rreceiver,ccontent);

if (ssender.equals("UK") && rreceiver.equals("UK"))
{
isNational = true;
}

else
{
isNational = false;
}
}

最佳答案

在 java8 中使用流就像过滤列表一样简单

long xx = myList.stream().filter(t -> t.isNational).collect(Collectors.counting());

或获取列表

List<NationalMessage> x = myList.stream().filter(t->t.isNational).collect(Collectors.toList());

关于java - 如何计算并仅返回 ArrayList 中为真的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44131772/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com