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

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   ...

Android - Basic Steps (Location & Maps)

Location Is composed by Latitude Longitude Time-stamp Accuracy Altitude Speed Bearing LocationProvider Types: Network  Wifi access points Cell phone towers GPS Passive Piggyback on the readings requested by other application Permissions Network  android.permission.ACCESS_COARSE_LOCATION android.permission.ACCESS_FINE_LOCATION GPS android.permission.ACCESS_FINE_LOCATION Passive Provider android.permission.ACCESS_FINE_LOCATION LocationManager System service for accessing location data getSystemService( Context.LOCATION_SERVICE ) Functions Determine the last known user location Register for location update Register to receive intents when the device nears or move away from a given geographic area LocationListener Defines callbacks methods that are called when Location or LocationProvider status change. Methods onLocationChanged(...) onProviderDisabled(...) onProviderEnabled(...) onStatusChan...

IIS - Permisions

IIS Permissions To enable the Active Directory connection in the IIS, follow the next steps: Go to IIS Go to Application Pool Select your App Pool Select Advanced Settings in the right side In the section Process Model Select in Identity value the property " NetworkService " You don´t need to restart your application