Ir al contenido principal

Java Fundamentals - Collections - Defining

Collection (Interface)


   --> List
Have an order, index


  -->Set
Have only one element without be duplicated

-->SortedSet
Have unique elements in an order.
You can´t add element in any position


  -->Queue
Has an order: FIFO Fisrt in First Out


  -->Deque
Has a doble ending queue: FIFO & LIFO


Key Collections

Both are collections in pairs: Keys/Values

  -->Map

  -->SortedMap
Can iterate over the Map and see the values in certain order


Implementation

 -->List
     -->ArrayList

getElement - ok
add - Fail
contains - fail
next - ok
remove - fail


     -->LinkedList

getElement - fail
add - ok
contains - fail
next - ok
remove - ok

  -->Set
      -->HashSet

  -->SortedSet
     -->TreeSet

  -->Queue
     -->PriorityQueue


In this case you need to create a Comparator in order to create the Priority.

Before JAVA 8

private static final Comparator<MY_CLASS> COMPARATOR = new Comparator<MY_CLASS>(){
     public int compare (final MY_CLASS o1, final MY_CLASS o2){
                     return o1.getAtribute.compareTo( o2.getAtribute() );
     }
}

In JAVA 8

private static final Comparator<MY_CLASS> COMPARATOR = comparing( MYCLASS::getAtribute );


PriorityQueue
private Queue<MY_CLASS> enquiries = new PriorityQueue<>(COMPARATOR);


  -->Deque
     -->LinkedList
    -->ArrayDeque

Return false if the queue is full 
boolean offerFirst(E e)
boolean offerLast(E e)

Throws an exception if the queue is full
void addFirst(E e)
void addLast(E e)

Returns null
E removeFirst()
E removeLast()

Throws exception when empty
E removeFirst()
E removeLast()

Returns null
E peekFirst()
E peekLast()

Throws exception when empty
E getFirst()
E getLast()

Commands to work as LIFO
void push(E e)
E pop()



  -->Map
    -->HashMap

keySet()
Return all the keys from the Map

final Map<Integer, CLASS> map = new HashMap<>();
final Set<Integer> keys = map.keySet();


values()
Return all the values from the map
final Collection<CLASS> values = map .values();


entrySet()
To iterate over a Map

 final Set<Map.Entry<Integer, CLASS>> entries = map.entrySet();
        for(Map.Entry<Integer, CLASS> entry : entries)
        {
            System.out.println(entry);
            System.out.println(entry.getKey() );
            System.out.println(entry.getValue() );
        }

JAVA 8
map.forEach((key, value) -> System.out.println(key + " -> " + value));



  -->SortedMap (Interface)
     -->TreeMap

K firstKey()
K lastKey()

SortedMap<K,V> tailMap( E fromKey)

SortedMap<K,V> headMap( E toKey)

SortedMap<K,V> subMap( E fromKey, E toKey)


  -->NavigableMap (Java 6)

Map.Entry<K,V> firstEntry()
Map.Entry<K,V> lastEntry()

Return and get element

Map.Entry<K,V> pollFirstEntry()
Map.Entry<K,V> pollLastEntry()

Map.Entry<K,V> floorEntry(K key)
Map.Entry<K,V> ceilingEntry(K key)

Get the next element (floorKey, ceilingKey)

K floorKey(K key)
K ceilingKey(K key)

By default the order is ascending
NavigableMap<K, V> descendingMap()
NavigableSet<K> descendingKeySet()

To iterate a through the keys
NavigableSet<K> navigableKeySet()

NavigableMap<K, V> tailMap( E fromKey, boolean includeElement)
NavigableMap<K, V> headMap( E toKey, boolean includeElement)

NavigableMap<K, V> subMap( E fromKey, boolean includeElement, E toKey, boolean includeElement)

   -->EnumSet



NEW METHODS - JAVA 8


getOrDefault
putIfAbsent
compute
computeIfPresent -  Review if an element exist otherwise it added

hashMap.computeIfPresent( KEY_TO_SEARCH,  (id) -> new MY_CLASS(id, ATTRIBUTE)

computeIfAbsent
merge - combine the key value, the value and the age

forEach

replaceAll -> Use lambda expressions
hashMap.replaceAll(  
    (key, value)  -> new Object( key,  object.getAttribute1(),  object.getAttribute2() + 10 )
);


Other collections

  • TreeMap
  • LinkedHashMap
  • WeakHashMap
    • Used as a cache
  • EnumMap
    • Store less than 64 elements


Collection Algorithms


Collections.rotate( LIST ,  #elementsToRotate )

Collections.shuffle( LIST ) 

Collections sort( My_Comparable )
In java 8 List contains sort method included


Collection Factories

Singleton
Set< Integer> set = Collections.singleton(1);
List<String> list = Collections.singletonList("one");
Map<Integer, String> amp  = Collections.singletonMap(1 , "a");

Empty Collections
Set< Integer> set = Collections.emptySet();
List<String> list = Collections.emptyList();
Map<Integer, String> amp  = Collections.emptyMap();


Collections.unmodifiableList( MY_LIST)
You can't change the list or a exception will be throw.

Collection Utilities

Collections.addAll( MY_LIST, element1, element2, ...);
Collections.min( MY_LIST, MY_COMPARATOR );
Collections.max( MY_LIST, MY_COMPARATOR );



Comentarios

Entradas populares de este blog

Python create package

Create a root folder Create a sub-folder "example_pkg" that contains the funtionallity packaging_tutorial/ example_pkg/ __init__.py In the root folder create the following structure  packaging_tutorial/ example_pkg/ __init__.py tests/ setup.py LICENSE README.md in the setup.py contains the configuration of the packages your package is found by find_packages() import setuptools with open ( "README.md" , "r" ) as fh : long_description = fh . read () setuptools . setup ( name = "example-pkg-YOUR-USERNAME-HERE" , # Replace with your own username version = "0.0.1" , author = "Example Author" , author_email = "author@example.com" , description = "A small example package" , long_description = long_description , long_description_content_type = "text/markdown" , url = "https://github.com/pypa/sam...

Rails - Basic Steps III

pValidations Validations are a type of ActiveRecord Validations are defined in our models Implement Validations Go to   root_app/app/models Open files  *.rb for each model Mandatory field validates_presence_of   :field Ex:   validates_presence_of    :title Classes The basic syntax is class MyClass        @global_variable                def my_method              @method_variable        end end Create an instance myInstance = MyClass.new Invoke a mehod mc.my_method class() method returns the type of the object In Ruby, last character of method define the behavior If ends with a question -> return a boolean value If ends with an exclamation -> change the state of the object Getter / Setter method def global_variable       return @global_variable end ...

Android - Basic Steps (Service)

Service Run in the main thread of the hosting application Android can kill the Service if need the resources Purpose Supporting inter-application method execution Performing background processing Start a Service Call Context.startService(Intent intent)\ To call from a Fragment use getActivity().getApplicationContext().startService( intentService); Executing the service After call startService(...)  In the Service is executed the method onStartCommand(...) If the method returns the constant START_NOT_STICKY then Android will not restart the service automatically if the the process is killedp Foreground To execute the service foreground call the method startForeground() Use this if the user is aware of the process Bind to a Service Call the method Context.bindService( Intent service ServiceConnection con int flags ) Send Toast from the Service On the method onStartCommand receive the message   ...