[JAVA] Let's use Set more [Collections Framework]

Java uses ArrayList instead of arrays. Hmm For people with a lot of knowledge

I want to have a value without duplication


List<String> list = new ArrayList<String>();

~ Various processing ~

String itemNo = get〇〇

if(list.contains(itemNo)){//Do not duplicate values
  list.add(itemNo);
}

You should use the set of collections instead of writing duplicate removal logic

Set is a collection with no duplicate elements Equals is used to prevent more than one instance of the same value.

By the way, the name Set is the English version of "set" in set theory (probably). Since the set does not allow duplicate elements (set of natural numbers, etc.)

I want to have a value without duplication


Set<String> set = new HashSet<String>();

~ Various processing ~

String itemNo = get〇〇

//↓ Deduplication is equals()No need to describe because set will do it using
//if(list.contains(itemNo)){//Do not duplicate values
set.add(itemNo);
//}

Easy to write & easy to read & easy to understand with few descriptions In the first place, it can be made clear that there is no duplication by using Set.

Will it be late?

Actual measurement

measurement


		List<Integer> list = new ArrayList<>();
		Long start = System.nanoTime();
		for(int i=0;i<100;i++){
			for(int j=0;j<100;j++){
				
				Integer num= i+j;

				if(!list.contains(num)){
				  list.add(num);
				}	
				
			}
			
		}
		Long end = System.nanoTime();

		System.out.println("list time:"+ String.valueOf(end - start));
		System.out.println(list);
		
		Set<Integer> set = new HashSet<>();
		Long start2 = System.nanoTime();
		for(int i=0;i<100;i++){
			for(int j=0;j<100;j++){
				Integer num= i+j;
				set.add(num);
			}
			
		}
		Long end2 = System.nanoTime();

		System.out.println("set time :"+String.valueOf(end2 - start2));
		System.out.println(set);

list time:10748381 [0, 1, 2, 3, 4, 5 ~ Omitted ~ set time :5471075 [0, 1, 2, 3, 4, 5 ~ Omitted ~ // * It happens to be in descending order, but the order is not guaranteed.

The difference was nearly double. I verified it several times, but the difference is about 1.2 to 3 times, and Set is faster. However, what I want to say here is not to use it for speeding up, You don't have to worry about performance degradation and don't use Set.

Recommended Posts

Let's use Set more [Collections Framework]
Let's use jcmd
[Swift] Let's use extension
[Swift] Let's use Segmented Control
[RSpec] Let's use FactoryBot [Rails]
[spring] Let's use Spring Data JPA
Java Collections Framework Review Notes
Let's use Swift Firebase Firebase Auth
How to set and use profile in annotation-based Configuration in Spring framework