Java – How to get the first item from Set

In Java, we can use Set.iterator().next() to get the first item from a java.util.Set JavaExample.java package com.mkyong; import java.util.HashSet; import java.util.Set; public class JavaExample { public static void main(String[] args) { Set<String> examples = new HashSet<>(); examples.add("1"); examples.add("2"); examples.add("3"); examples.add("4"); examples.add("5"); System.out.println(examples.iterator().next()); // java 8 System.out.println(examples.stream().findFirst().get()); } } Output 1 1 References Oracle doc – …

Read more

Java – How to compare two Sets

In Java, there is no ready make API to compare two java.util.Set 1. Solution Here’s my implementation, combine check size + containsAll : SetUtils.java package com.mkyong.core.utils; import java.util.Set; public class SetUtils { public static boolean equals(Set<?> set1, Set<?> set2){ if(set1 == null || set2 ==null){ return false; } if(set1.size()!=set2.size()){ return false; } return set1.containsAll(set2); } …

Read more

What is the different between Set and List

Set and List explanation Set – Stored elements in unordered or shuffles way, and does not allow duplicate values. List – Stored elements in ordered way, and allow duplicate values. Set and List Example import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class SetAndListExample { public static void main( String[] args ) { System.out.println("List …

Read more