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

BI - SSIS ( Basics I )

SSIS - Basic Concepts Tasks Bulk Insert Task—Loads data into a table by using the BULK INSERT SQL command. Data Flow Task—This is the most important task that loads and transforms data into an OLE DB Destination. Execute Package Task—Enables you to execute a package from within a package, making your SSIS packages modular. Execute Process Task—Executes a program external to your package, like one to split your extract file into many files before processing the individual files. Execute SQL Task—Executes a SQL statement or stored procedure. File System Task—This task can handle directory operations like creating, renaming, or deleting a directory. It can also manage file operations like moving, copying, or deleting files. FTP Task—Sends or receives files from an FTP site. Script Task—Runs a set of VB.NET or C# coding inside a Visual Studio environment. Send Mail Task—Sends a mail message through SMTP. Analysis Services Processing Task—This task processes a SQL Server A...

TOGAF9

Kinds of Architectures Business Architecture / Business Process Architecture    Define the business strategy, governance, organization and key business processes Data Architecture    Describe the structure of an organization logical and physical data assets and data resources Application Architecture    Describe a blueprint for the individual application systems to be deploy, interactions and  their relationships to the core business processes of the organization Technology Architecture    Describe the logical software and hardware capabilities that are required to support the deployment of business data and application services. This includes middle-ware infrastructure, networks, communications, processing standards  Architecture Governance Increase transparency of accountability, and informed delegation of authority Controlled risk management Protection of the existing asset base through maximizing  re-us...