简体   繁体   English

如何从 java 中的 class object 列表中获取第一个匹配元素的索引(不使用任何第三方库)

[英]How to get index of first matched element from the list of class object in java (Without using any third party Library)

I have a List of class object (List).我有一个 class object 列表(列表)。 I want to get the index of the first user from the list with a particular user status.我想从具有特定用户状态的列表中获取第一个用户的索引。

public enum UserStatus {
    CREATED("CREATED"),
    AVAILABLE("AVAILABLE"),
    CHECKIN("CHECKIN"),
    CHECKOUT("CHECKOUT"),
    ON_TRIP("ONTRIP"),
    UNAVAILABLE("UNAVAILABLE");
 }

  Class Users{
        private Long id;
        private Long userId;        
        private UserStatus userStatus;
        private Date createdAt;
    }

Class Main{
    public static void main(String args[]){
        List<Users> userList = getListofUser(); // this method will give me list of users

        // here I want to find the first user whose status is AVAILABLE

    }
}

I am looking for similar to List indexOf() method我正在寻找类似于 List indexOf() 方法

You can do this using Java streams and optionals您可以使用 Java 流和选项来执行此操作

Optional<User>firstMatchingUserOptional = userList.stream.filter(user -> user.getUserStatus().equals(UserStatus.AVAILABLE)).findFirst();

if(firstMatchingUserOptional.isPresent())
    int firstMatchingUserIndex = userList.indexOf(firstMatchingUserOptional.get());

Just iterate through list and when you find AVAILABLE return from the loop.只需遍历列表,当您发现AVAILABLE从循环返回时。

Users getFirstAvailableUser(List<Users> userList ) {

   Iterator<Users> it = userList.iterator();
   while ( it.hasNext() ) {
      Users curr = it.next();
      if ( curr.getUserStatus() == UserStatus.AVAILABLE ) {
         return curr;
      }
   }

   return null;
}

You can use您可以使用

int index = IntStream.range(0, userList.size())
    .filter(ix -> userList.get(ix).getUserStatus() == UserStatus.AVAILABLE)
    .findFirst().orElse(-1);

If you don't want to use the Stream API or suspect the list not to have efficient random access, you can use如果您不想使用 Stream API 或怀疑该列表没有有效的随机访问,您可以使用

int index = -1;
for(ListIterator<Users> i = userList.listIterator(); i.hasNext(); ) {
    if(i.next().getUserStatus() == UserStatus.AVAILABLE) {
        index = i.previousIndex();
        break;
    }
}

As a side note, the class name should reflect what a single instance of the class represents, ie User instead of Users when one object represents a single user.作为旁注,class 名称应反映 class 的单个实例所代表的内容,即当一个 object 代表单个用户时, User而不是Users Further, there is no need to pass the names of the enum constants to themselves.此外,无需将enum常量的名称传递给它们自己。 They do already know their names.他们确实已经知道他们的名字。

When you declare the type as当您将类型声明为

public enum UserStatus {
   CREATED,
   AVAILABLE,
   CHECKIN,
   CHECKOUT,
   ON_TRIP,
   UNAVAILABLE
}

calling UserStatus.AVAILABLE.name() will give you the string "AVAILABLE" and calling UserStatus.valueOf("AVAILABLE") will return the constant UserStatus.AVAILABLE .调用UserStatus.AVAILABLE.name()将为您提供字符串"AVAILABLE"并调用UserStatus.valueOf("AVAILABLE")将返回常量UserStatus.AVAILABLE You don't need to implement such logic yourself.你不需要自己实现这样的逻辑。

you can use for loop;你可以使用 for 循环;

something like就像是

`for(User tempUser : userList){
 if(tempUser.UserStatus.equals(UserStatusTemp)){
 //do job
 break;
  }
  }`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用第三方库的情况下使用Java中另一个CSV文件中的值创建CSV文件 - How to create a CSV file using the values from another CSV file in Java without using third party library Java中的HttpClient而不使用任何第三方库 - Httpclient in java without using any third party libraries 如何在不使用Android中任何第3方库的情况下从基于json的api获取json数据? - How to get json the data from json based api without using any 3rd party library in Android? 如何在没有 jsoup 或任何其他第三方的情况下在 java 上读取 html? - How to read html on java without jsoup or any other third party? 使用Clojure中的Java第三方库的步骤 - Steps in using a java third party library from clojure 如何模拟来自第三方库的类的静态调用 - How to mock a static call on a class from a third-party library 如何只替换列表的第一个元素<Character>使用 java 流而不对列表的其余部分进行任何更改? - How to replace only the first element of a List<Character> using java streams without making any changes to the rest of the list? 用Java获取第三方库版本 - get third party library versions in Java 是否可以在没有任何第三方库的情况下使用@RequestBody将JSON转换为Java bean - Is it possible to covert JSON to java bean with @RequestBody without any third party library 使用并行流从Java列表中获取Pojo,而无需使用任何类型的索引 - Get Pojo from a java list using parallel stream without using any kind of index
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM