Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 查找ID的编号';s的状态为';R';在Java中的对象列表中_List_Object - Fatal编程技术网

List 查找ID的编号';s的状态为';R';在Java中的对象列表中

List 查找ID的编号';s的状态为';R';在Java中的对象列表中,list,object,List,Object,我有一个对象列表,其中每个对象都有Id和状态。 我如何找到具有“R”状态的ID的不同数量? 例如: 身份证状态 5 R 1秒 5 R 2R 1 R 5 R 在本例中,ID的计数为2,因为ID(5和2)在Java 8中的状态为“R”,这非常简单: class Foo { int id; char status; @Override public boolean equals(Object o){ if (this == o) return true

我有一个对象列表,其中每个对象都有Id和状态。 我如何找到具有“R”状态的ID的不同数量? 例如: 身份证状态 5 R 1秒 5 R 2R 1 R 5 R


在本例中,ID的计数为2,因为ID(5和2)在Java 8中的状态为“R”

,这非常简单:

class Foo {
    int id;
    char status;

    @Override
    public boolean equals(Object o){
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        return ( id == ((Foo) o).id ) && ( status == ((Foo) o).status );
    }

    @Override
    public int hashCode(){
        return id << 8 + status;    // Example, supposing id is not too big
    }
}

List<Foo> list;

int result = Stream.of(list).distinct().filter(x -> x.status == 'R').count();
class-Foo{
int-id;
字符状态;
@凌驾
公共布尔等于(对象o){
如果(this==o)返回true;
如果(o==null | | getClass()!=o.getClass())返回false;
返回(id==((Foo)o.id)和&(status==((Foo)o.status);
}
@凌驾
公共int hashCode(){
返回id x.status=='R').count();
首先将
Foo
列表
转换为
Foo
,然后消除重复项,根据状态字段的值过滤元素。最后计算剩余元素


要正确消除重复,必须重载
equals
hashCode
方法。

对于Java,我们的框架中没有Java 8。还有其他方法吗?@Vincz77添加一个.distinct()计数前。示例中有重复项。我们希望在Foo类中定义了equals和hashcode:)您正在设置一个id,以设置其状态是否为“R”。如果其状态不是“R”,该怎么办?我们必须排除该项。
    Set<Integer> match = new HashSet<>();
    for (Item item : myList) {
        if (item.status=='R') match.add(item.id);
    }
    System.out.println(match.size());