Home Java javaTutorial Java determines whether an instance of an element exists in an array or collection

Java determines whether an instance of an element exists in an array or collection

Jan 23, 2017 pm 04:47 PM

Introduction:

Today a friend in the group asked "How to know whether an array collection already exists the current object?" Everyone knows about circular comparison, including me, a great group member. Is there any other way? Let’s take a look at this article.

Text:

The people you can find here are all programmers. It should be clearer to directly enter the code.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

import java.io.Serializable;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collection;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

   

public class Test implements Serializable {

   

  private static final long serialVersionUID = 2640934692335200272L;

   

  public static void main(String[] args) {

   

    // data segment

    String[] SAMPLE_ARRAY = new String[] { "aaa", "solo", "king" };

    String TEST_STR = "king";

    Collection TEMPLATE_COLL = new ArrayList();

    TEMPLATE_COLL.add("aaa");

    TEMPLATE_COLL.add("solo");

    TEMPLATE_COLL.add("king");

    // <- data segment

   

    // 1, 字符串数组是否存在子元素

    // 1-1, 直接使用API

    Arrays.sort(SAMPLE_ARRAY);

    int index = Arrays.binarySearch(SAMPLE_ARRAY, TEST_STR);

    System.out.println("1-1_sort-binarySearche:"

        + ((index != -1) ? true : false));

   

    // 1-2, 使用正则(因Arrays.toString()引入了“, [ ]”故只在有限环境下可靠)

    String tmp = Arrays.toString(SAMPLE_ARRAY);

    Pattern p = Pattern.compile("king");

    Matcher m = p.matcher(tmp);

    System.out.println("1-2_toString-Regex:" + m.find());

   

    // 1-3, 都会写循环,略过。

    // TODO: 循环数据依次比对,此处略去5行代码。

   

    // 2, 集合是否存在子元素

    // 2-1, 最常用的contains

    System.out.println("2-1_contains:" + TEMPLATE_COLL.contains(TEST_STR));

   

    // 2-1-1, 扩展:

    // 按模板集合,将当前集合分为“模板已存在”与“不存在”两个子集。

    Collection coll = new ArrayList<String>();

    coll.add("aaa");

    coll.add("bbb");

    coll.add("ccc");

    // 完整复制集合

    Collection collExists = new ArrayList(coll);

    Collection collNotExists = new ArrayList(coll);

   

    collExists.removeAll(TEMPLATE_COLL);

    System.out.println("2-1-1_removeAll[exist]:" + collExists);

    collNotExists.removeAll(collExists);

    System.out.println("2-1-1_removeAll[notexist]:" + collNotExists);

   

  }

   

}

Copy after login

Running results:

1

2

3

4

5

1-1_sort-binarySearche:true

1-2_toString-Regex:true

2-1_contains:true

2-1-1_removeAll[exist]:[bbb, ccc]

2-1-1_removeAll[notexist]:[aaa]

Copy after login

Let’s summarize~. =

1) There are at least three types of arrays:

A) binarySearch(,). But the condition is that it needs to be sorted in advance, and the overhead needs to be considered.
B) Regex. However, the array needs to be converted into a string. The method provided by the Arrays class will introduce the three delimiters ", [ ]", which may affect the determination result.
C) Circular comparison.

2) There are at least two types of collections:

A) Loop. If it is only determined to exist by default (non-customized existence), it is recommended not to consider it directly.
B) contains. If you can get closer, do it decisively.

3) Sets provide operations similar to "addition and subtraction", so you can pay attention to them.

The above is the entire content of the java examples brought by the editor to determine whether an element exists in an array or collection. I hope you will support the PHP Chinese website~

More java determination arrays Or whether there is an instance of a certain element in the collection. For related articles, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? What is the difference between memory leaks in Java programs on ARM and x86 architecture CPUs? Apr 19, 2025 pm 11:18 PM

Analysis of memory leak phenomenon of Java programs on different architecture CPUs. This article will discuss a case where a Java program exhibits different memory behaviors on ARM and x86 architecture CPUs...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to convert names to numbers to implement sorting within groups? How to convert names to numbers to implement sorting within groups? Apr 19, 2025 pm 01:57 PM

How to convert names to numbers to implement sorting within groups? When sorting users in groups, it is often necessary to convert the user's name into numbers so that it can be different...

See all articles