Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. public static int searchElement(final List<? extends Animal> list, final int weight) {
  2. return Collections.binarySearch(list, weight...);
  3. }
  4.  
  5. import java.util.ArrayList;
  6. import java.util.Arrays;
  7. import java.util.Collections;
  8. import java.util.List;
  9. import java.util.function.Function;
  10.  
  11. class Animal implements Comparable<Animal>
  12. {
  13. private final int weight;
  14.  
  15. Animal(int weight)
  16. {
  17. this.weight = weight;
  18. }
  19.  
  20. public int getWeight()
  21. {
  22. return weight;
  23. }
  24.  
  25. @Override
  26. public int compareTo(Animal that)
  27. {
  28. return Integer.compare(this.weight, that.weight);
  29. }
  30. }
  31.  
  32. public class CollectionBinarySearch
  33. {
  34. public static void main(String[] args)
  35. {
  36. List<Animal> animals = new ArrayList<Animal>();
  37. animals.add(new Animal(10));
  38. animals.add(new Animal(40));
  39. animals.add(new Animal(20));
  40. animals.add(new Animal(90));
  41. animals.add(new Animal(290));
  42. animals.add(new Animal(130));
  43.  
  44. Collections.sort(animals);
  45.  
  46. System.out.println(searchWithInstance(animals, 90));
  47. System.out.println(searchWithInstance(animals, 50));
  48.  
  49. System.out.println(searchWithArray(animals, 90));
  50. System.out.println(searchWithArray(animals, 50));
  51.  
  52. System.out.println(searchWithFunction(animals, Animal::getWeight, 90));
  53. System.out.println(searchWithFunction(animals, Animal::getWeight, 50));
  54.  
  55. }
  56.  
  57. public static int searchWithInstance(
  58. final List<? extends Animal> list, final int weight) {
  59. return Collections.binarySearch(list, new Animal(weight));
  60. }
  61.  
  62. public static int searchWithArray(
  63. final List<? extends Animal> list, final int weight) {
  64. int[] array = list.stream().mapToInt(Animal::getWeight).toArray();
  65. return Arrays.binarySearch(array, weight);
  66. }
  67.  
  68. // Adapted from Collections#binarySearch
  69. private static <T, K extends Comparable<? super K>> int searchWithFunction(
  70. List<? extends T> list, Function<? super T, K> keyExtractor, K key) {
  71. int low = 0;
  72. int high = list.size()-1;
  73. while (low <= high) {
  74. int mid = (low + high) >>> 1;
  75. T midVal = list.get(mid);
  76. int cmp = keyExtractor.apply(midVal).compareTo(key);
  77. if (cmp < 0)
  78. low = mid + 1;
  79. else if (cmp > 0)
  80. high = mid - 1;
  81. else
  82. return mid; // key found
  83. }
  84. return -(low + 1); // key not found
  85. }
  86.  
  87. }
  88.  
  89. Collections.binarySearch(Lists.transform(animals, Animal::weight), searchWeight);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement