Java8判断字段是否在数组中

1.判断是否在int数组中,例:

Integer[] intList = {1, 2, 3};
boolean contains = IntStream.of(intList).anyMatch(x -> x == 1);
System.out.println(contains); // 返回true
contains = IntStream.of(intList).anyMatch(x -> x == 5);
System.out.println(contains); // 返回false

2.判断是否在String数组中,例:

String[] strList = {"AB", "AC", "AD", "AE"};
boolean contains = Arrays.stream(strList).anyMatch("AC"::equals);
System.out.println(contains); // 返回true
contains = Arrays.stream(strList).anyMatch("EE"::equals);
System.out.println(contains); // 返回false

3.判断是否在Object中,例:

public class UserVo{
    private Integer id;
    private String userName;
}

List userList = new ArrayList<>();
UserVo vo = new UserVo();
vo.setId(1);
vo.setUserName("ll");
userList.add(vo);
vo = new UserVo();
vo.setId(2);
vo.setUserName("uu");
userList.add(vo);

boolean contains = userList.stream().anyMatch(user -> user.getId().equals(1));
System.out.println(contains); // 返回true
contains = userList.stream().anyMatch(user -> user.getId().equals(3));
System.out.println(contains); // 返回false

 

你可能感兴趣的:(Java)