2022-06-09

Java Collections

 https://www.programcreek.com/2014/04/check-if-array-contains-a-value-java/

1. Four Different Ways to Check If an Array Contains a Value

1) Using List:

public static boolean useList(String[] arr, String targetValue) {
	return Arrays.asList(arr).contains(targetValue);
}

2) Using Set:

public static boolean useSet(String[] arr, String targetValue) {
	Set<String> set = new HashSet<String>(Arrays.asList(arr));
	return set.contains(targetValue);
}

3) Using a simple loop:

public static boolean useLoop(String[] arr, String targetValue) {
	for(String s: arr){
		if(s.equals(targetValue))
			return true;
	}
	return false;
}

4) Using Arrays.binarySearch():
binarySearch() can ONLY be used on sorted arrays. If the array is sorted, you can use the following code to search the target element:

public static boolean useArraysBinarySearch(String[] arr, String targetValue) {	
	int a =  Arrays.binarySearch(arr, targetValue);
	if(a > 0)
		return true;
	else
		return false;
}
Comparator<Arrow> cmp = Comparator
        .comparing(Arrow::getWeight)
        .thenComparing(Arrow::getCount, Comparator.reverseOrder())
        .thenComparing((a, b) -> Character.compare(a.ch, b.ch));

listChar.sort(cmp);
 
List<Employee> sortedEmployees = employees.stream()
                .sorted(cmp).collect(Collectors.toList());

////////////////////////////////////////////////////////////////////////////////////////////////////////// 

 Collections.sort(scores, new Comparator<Score>() {

        public int compare(Score o1, Score o2) {
            return o2.getScores().get(0).compareTo(o1.getScores().get(0));
        }
    });
Collections.sort(scores, (s1, s2) -> { return s1 - s2; });
Collections.binarySearch(cats, key);

String s = list.stream().map(Objects::toString)
.sorted(Comparator.reverseOrder()).collect(Collectors.joining(""));
int[] arr = {1,2,3};
var list = Arrays.stream(arr).boxed().toList();

list.subArray(int begin, int end)

No comments: