miércoles, 27 de noviembre de 2019

Collections 2019 Java

Collections 2019 Java



https://github.com/jalbertomr/Collections2019Java.git

Datos Provider

public class Datos {

    List<String> listNombres = new ArrayList<>();
    String[] arrNombres;
    String nombresjuntos = "Álan     Jacinto Martinez Alicia     Jesús     Mirta Andrea     Josefina     Mónica " +
    "Andrés     Juan     Nicolás   Antonia     Juana     Noé    Antonio     Juano     Noelia    Azul     Julia     Paula " +
    "Bartolomé     Julián     Pomponio  Belén     Juliana     Renzo   Celeste     Julio     Rodrigo " +
    "Edgardo     Leandra     Rodriguez    Felicia     Luis     Romina     Florencia     Luisa     Rosario" +
    "Gaspar     Marcelo     Tato   Gerardo     Marcos     Tomás   Gimenez     María     Victor   Gonzalo     Mariano     Yayo "+
    "Gustavo     Martín     Zulema";
    String colores = "Rojo Naranga Amarillo Verde Azul Índigo Violeta";
    String[] arrColores;
    List<String> listColores = new ArrayList<>();

    public Datos() {
        StringTokenizer stoken = new StringTokenizer( nombresjuntos);
        //System.out.println( "stoken.countTokens(): " + stoken.countTokens());
        arrNombres = new String[ stoken.countTokens()];
        int i = 0;
        StringBuilder element = new StringBuilder();

        //System.out.println("Tokens");
        while( stoken.hasMoreTokens()){
            element.setLength(0); element.append( stoken.nextToken());
            //System.out.print( element + ", ");
            arrNombres[ i++ ] = element.toString();
        }
        //System.out.println();

        listNombres = Arrays.asList( arrNombres);
        // Display the filled String[] using Arrays.stream
        //Arrays.stream(arrNombres).forEach(s -> System.out.print(s + " "));

        stoken = new StringTokenizer( colores );
        arrColores = new String[ stoken.countTokens()];

        while(stoken.hasMoreTokens()){
            listColores.add( stoken.nextToken());
        }
        arrColores = listColores.toArray( arrColores);
        //Arrays.stream(arrColores).forEach(s -> System.out.println(s + " "));
    }
};


ArraysLab

public class ArraysLab {
    public ArraysLab() {
        int arrint[] = {10, 20, 30, 40, 50, 60, 70};
        int[] arrint2 = new int[8];
        int[] arrint3 = new int[]{1, 2, 3};
        String arrstr[] = {"cero", "uno", "dos", "tres", "cuatro"};
        String[] arrstr2 = {"cero", "uno", "dos", "tres", "cuatro"};
        String[] arrstr3 = new String[]{"cero", "uno", "dos", "tres", "cuatro"};

        String[][] arrarrStr = {{"cero", "uno", "dos", "tres", "cuatro"},
                {"alfa", "beta", "gamma", "delta", "epsilon"},
                {"000", "1111", "2222", "33333", "44444"}};
        Arrays.stream( arrarrStr).forEach( arrStr -> Arrays.stream( arrStr).forEach( s->System.out.print(s+" ") ) );
        System.out.println();
        Arrays.stream( arrarrStr).forEach( arrStr -> System.out.println(Arrays.stream( arrStr).map( s-> s.concat(" ")).collect(Collectors.toList()) ) );

        displayArrInt(arrint);
        displayArrInt(arrint2);
        displayArrInt(arrint3);

        Arrays.fill(arrint2, 123);
        displayArrInt(arrint2);

        System.out.println(Arrays.binarySearch(arrint, 40));   // 3
        System.out.println( "arrstr[ new Random().nextInt( arrstr.length) ] : " + arrstr[ new Random().nextInt( arrstr.length) ]);

        System.out.println("Fill witn Random");
        arrIntFillRandom(arrint);
        displayArrInt(arrint);
        Arrays.sort(arrint);
        displayArrInt(arrint);

        int[] arrint4 = Arrays.copyOf(arrint, arrint.length + 10);
        displayArrInt(arrint4);

        System.out.println(Arrays.equals(arrint, arrint2));
        System.out.println(Arrays.hashCode(arrint));
        System.out.println(Arrays.toString(arrint));

        // List<Integer>   <- int[]

        List<Integer> listInteger = new ArrayList<>();
        for (int i = 0; i < arrint.length; i++) {
            listInteger.add(arrint[i]);
        }
        System.out.println(listInteger.toString() + " size: " + listInteger.size());

        List<Integer> listInt2 = Arrays.asList(2, 3, 4, 5);
        System.out.println(listInt2.toString() + " size: " + listInt2.size());

        //List<String>
        List<String> listStr2 = Arrays.asList("luis", "juan");
        System.out.println(listStr2.toString());
    }

    private void displayArrInt(int[] arrint) {
        for (int i = 0; i < arrint.length; i++) {
            System.out.print(arrint[i] + ", ");
        }
        System.out.println();
    }

    private void arrIntFillRandom(int[] arrint) {
        for (int i = 0; i < arrint.length; i++){
            arrint[i] = (int) Math.round((Math.random() * 100));
        }
    }

}


ListLab

public class ArrayListLab {

    public ArrayListLab() {
        int intPrimitive = 12;
        Integer intObj = 130;
        double doublePrimitive = 234.33;
        Double doubleObj = 5434.654;

        intPrimitive = (int) doublePrimitive;
        intPrimitive = doubleObj.intValue();
        intPrimitive = (int) Math.round(doubleObj);

        intPrimitive = intObj.intValue();

        // Lists
        int[] arrint = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
        System.out.println(arrint.length);
        List<Integer> listInt = new ArrayList<>(); //                    ArrayList
        //List<Integer> listInt = Arrays.asList( 2, 3, 4, 7, 34, 21); // List
        for (int i = 0; i < arrint.length; i++){
            listInt.add( arrint[i]);
        }

        Integer[] arrInteger = { 23,54,2,24,65,33,23,66,98,65};
        List<Integer> listInt2 = new ArrayList<Integer>( Arrays.asList( arrInteger ) );

        displayListIntFor(listInt);
        displayListIterator(listInt);
        displayListStream(listInt);
        System.out.println("listInt2");
        displayListIntFor(listInt2);

        System.out.println("arrint[0]: " + arrint[0] );
        System.out.println("listInt.get(0): " + listInt.get(0));
        //remove
        listInt.remove( new Integer(3)); // remove object Integer 3
        displayListIntFor(listInt);
        listInt.remove( listInt.size() - 1 );  // remove index, the last element
        displayListIntFor(listInt);

        List<String> listStrA = new ArrayList<>();
        for (int i = 0; i < 6; i++){
            listStrA.add( String.valueOf( i ) );
            listStrA.add( Integer.toString( i ));
            displayListIterator( listStrA);
        }

/*
        List<String> listStr = Arrays.asList("A","E","I","O","U"); //List
        displayListIterator(listStr);
        listStr.remove("A");     //can not be accessed
*/
        //List.add() ArrayList.add()
        List<String> listStr = new ArrayList<>();
        listStr.add("A"); listStr.add("B");listStr.add("A");listStr.add("C");listStr.add("A");
        listStr.add("D"); listStr.add("A");listStr.add("E");listStr.add("A");listStr.add("F");
        displayListIterator(listStr);
        listStr.add(1,"addAtIndex1");
        displayListIterator(listStr);
        listStr.remove("addAtIndex1");
        displayListIterator(listStr);

        //List.addAll(index, collection)
        // create the Arraylist<String> filled from an array of string
        String[] arrStringBLOCK = {"B","L","O","C","K"};
        List<String> listStrBlock = new ArrayList<>( arrStringBLOCK.length);
        for (int i = 0; i < arrStringBLOCK.length; i++){
            listStrBlock.add(arrStringBLOCK[i]);
        }
        displayListIterator(listStrBlock);

        listStr.addAll(listStrBlock);
        displayListIterator(listStr);

        listStr.addAll(2,listStrBlock);
        displayListIterator(listStr);

        // List.get(index) , List.set(index, object)
        System.out.println( "listStr.get(0): " + listStr.get(0) );
        System.out.println( "listStr.get(19): " + listStr.get(19) );
        System.out.println("listStr.set(19,\"ZZ\") :" + listStr.set(19,"ZZ") );
        displayListIterator(listStr);

        System.out.println("listStr.lastIndexOf(\"A\"): " + listStr.lastIndexOf("A"));
        List<String> miSubListStr = listStr.subList(0, 4);
        System.out.println("listStr.subList(0, 4) : "); displayListIterator( miSubListStr);
        listStr.remove("A");
        displayListIterator(listStr);
/*
        listStr.add("A");
        displayListIterator(listStr);
        while (listStr.remove("A")){     //remove all the "A" and display the list each iteration
            displayListIterator(listStr);
        }
*/
    }

    private void displayListIterator(List list) {
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.print( iterator.next() + ", ");
        }
        System.out.print("size: " + list.size());
        System.out.println();
    }

    private void displayListIntFor(List<Integer> list) {
        for ( int e : list)  {
            System.out.print( e + ", ");
        }
        System.out.print("size: " + list.size());
        System.out.println();
    }


    private void displayListIntForOld(List<Integer> list) {
        for ( int i = 0; i < list.size(); i++) {
            System.out.print( list.get(i) + ", ");
        }
        System.out.print("size: " + list.size());
        System.out.println();
    }

    private void displayListStream(List list) {
        list.stream().forEach(e -> System.out.print(e + ", "));
        System.out.print("size: " + list.size());
        System.out.println();
    }
}

LinkedListLab

public class LinkedListLab {
    LinkedListLab() throws InterruptedException {
        System.out.println("LinkedListLab");
        /*
        LinkedList.addFirst(Object E);
        LinkedList.addLast( Object E);
         */

        LinkedList<String> miLList = new LinkedList<>();
        LinkedList<String> miLListRESP = new LinkedList<>();
        //Collections.shuffle(list, new Random());
        displayListIterator(miLList);
        miLList.addFirst("addFirst1");
        miLList.addFirst("addFirst2");
        miLList.addFirst("addFirst3");
        miLList.addLast("addLast1");
        miLList.addLast("addLast2");
        miLList.addLast("addLast3");
        miLListRESP.addAll(miLList);
        displayListIterator(miLListRESP);
        displayListIterator(miLList);

        System.out.println("miLList.getFirst(): " + miLList.getFirst());
        System.out.println("miLList.getLast(): " + miLList.getLast());

        System.out.println("miLList.remove(): " + miLList.remove());
        System.out.println("miLList.remove(): " + miLList.remove());
        System.out.println("miLList.remove(): " + miLList.remove());
        System.out.println("miLList.remove(): " + miLList.remove());

        miLList.clear();
        miLList.addAll(miLListRESP);
        displayListIterator(miLList);
        System.out.println("miLList.set( 2,\"set(2,obj)\"): " + miLList.set(2, "set(2,obj)"));
        displayListIterator(miLList);
        System.out.println("miLList.get(3): " + miLList.get(3));

        System.out.println("miLList.add(\"add1\"): " + miLList.add("add1"));  //add at last
        System.out.println("miLList.add(\"add2\"): " + miLList.add("add2"));  //add at last
        displayListIterator(miLList);
        System.out.println("miLList.remove(2): " + miLList.remove(2));
        displayListIterator(miLList);

        miLList.clear();
        miLList.addAll(miLListRESP);
        displayListIterator(miLList);
        displayListIterator(miLListRESP);
        System.out.println("miLListRESP.containsAll( miLList): " + miLListRESP.containsAll(miLList));
        miLList.add("EXTRA");
        displayListIterator(miLList);
        displayListIterator(miLListRESP);
        System.out.println("miLListRESP.containsAll( miLList): " + miLListRESP.containsAll(miLList));

        Spliterator spliterator = miLList.spliterator();

        Datos datos = new Datos();
        miLList.clear();
        miLList.addAll(datos.listNombres.subList(0, 10));
        miLList.stream().forEach(s -> System.out.print(s + " "));
        System.out.println();

        miLList.sort(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return removeAccents(o1).compareTo(removeAccents(o2));
            }
        });
        miLList.stream().forEach(s -> System.out.print(s + " "));
        System.out.println();

        // LikedList  add , Remove  better performance than ArrayList
        //            get, set      lower perforance than ArrayList

        miLList.clear();
        miLList.addAll(datos.listNombres.subList(0, 5));
        displayLinkedList(miLList);
        ListIterator<String> listIterator = miLList.listIterator();
        System.out.println("ListIterator.hasNext()  ListIterator.next()");
        int i = 1;
        int showtime = 100;
        while (listIterator.hasNext()) {
            System.out.println(String.format("%" + 12 * i + "s", listIterator.next()));
            Tsleep(showtime);
            i++;
        }

        System.out.println("ListIterator.hasPrevious()  ListIterator.previous()");
        i--;
        while (listIterator.hasPrevious()) {
            System.out.println(String.format("%" + 12 * i + "s", listIterator.previous()));
            Tsleep(showtime);
            i--;
        }

        displayLinkedList(miLList);

        i = 1;
        while (listIterator.hasNext()) {
            if (listIterator.nextIndex() == 2) break;
            System.out.println(String.format("%" + 12 * i + "s", listIterator.next()));
            Tsleep(showtime);
            i++;
        }

/*
|      Álan||   Jacinto||  Martinez||    Alicia||     Jesús|
        Álan
                 Jacinto
 */
        System.out.println("listIterator.add(\"ADDIT\");");
        listIterator.add("ADDIT");
        displayLinkedList(miLList);
/*
|      Álan||   Jacinto||     ADDIT||  Martinez||    Alicia||     Jesús|
 */
        System.out.println("if (listIterator.hasPrevious()) { listIterator.previous(); listIterator.remove(); }");
        if (listIterator.hasPrevious()) {
            listIterator.previous();
            listIterator.remove();
        }
        displayLinkedList(miLList);

        System.out.println("listIterator.nextIndex(): " + listIterator.nextIndex());
        System.out.println("listIterator.add(\"ADDagain\");");
        listIterator.add("ADDagain");
        displayLinkedList(miLList);
/*
|      Álan||   Jacinto||  ADDagain||  Martinez||    Alicia||     Jesús|
 */

        System.out.println("listIterator move to the end");
        while (listIterator.hasNext()) {
            listIterator.next();
        }
        System.out.println("listIterator.add(\"AlFinal\");");
        listIterator.add("AlFinal");
        displayLinkedList(miLList);
/*
|      Álan||   Jacinto||  ADDagain||  Martinez||    Alicia||     Jesús||   AlFinal|
 */

        System.out.println("if ( listIterator.hasPrevious() ) { listIterator.previous();  }");
        System.out.println("listIterator.remove();");
        if (listIterator.hasPrevious()) {
            listIterator.previous();
        }
        listIterator.remove();
        displayLinkedList(miLList);
/*
|      Álan||   Jacinto||  ADDagain||  Martinez||    Alicia||     Jesús|
 */

        System.out.println("move to the begining and add");
        while (listIterator.hasPrevious()) listIterator.previous();
        listIterator.add("addBegin");
        displayLinkedList(miLList);
/*
|  addBegin||      Álan||   Jacinto||  ADDagain||  Martinez||    Alicia||     Jesús|
 */

        System.out.println("if (listIterator.hasPrevious()) listIterator.previous();");
        System.out.println("listIterator.remove();");
        if (listIterator.hasPrevious()) listIterator.previous();
        listIterator.remove();
        displayLinkedList(miLList);
/*
|      Álan||   Jacinto||  ADDagain||  Martinez||    Alicia||     Jesús|
 */
        System.out.println("miLList.remove(\"ADDagain\")" + miLList.remove("ADDagain"));
        miLList.remove("ADDagain");
        displayLinkedList(miLList);
    }

    public  static String removeAccents(String text) {
        return text == null ? null : Normalizer.normalize(text, Normalizer.Form.NFD)
                .replaceAll("\\p{InCOMBINING_DIACRITICAL_MARKS}+","");
    }

    private void displayLinkedList( LinkedList linkedList) {
        int cellLength = 10;
        linkedList.stream()
                .map(s -> String.format("|%" + cellLength + "s|", s))
                .forEach( s -> System.out.print( s));
        System.out.println();
    };

    private void Tsleep(int miliseconds)  {
        try {
            Thread.sleep( miliseconds);
        } catch( InterruptedException ie) {
            System.err.format( "InterruptedException: %s%n" + ie);
        };
    }

    private void displayListIterator(List list) {
        System.out.print("size: " + list.size() + " ");
        Iterator iterator = list.iterator();
        while (iterator.hasNext()) {
            System.out.print( iterator.next() + ", ");
        }
        System.out.println();
    }

    private void displayListIntFor(List<Integer> list) {
        System.out.print("size: " + list.size() + " ");
        for ( int i = 0; i < list.size(); i++) {
            System.out.print( list.get(i) + ", ");
        }
        System.out.println();
    }

    private void displayListStream(List list) {
        System.out.print("size: " + list.size() + " ");
        list.stream().forEach(e -> System.out.print(e + ", "));
        System.out.println();
    }
}

QueueLab

public class QueueLab {
    public QueueLab() {        System.out.println("QueueLab");
        /*

         */

        Queue<String> miQueue = new LinkedList<>();
        Queue<String> miQueueRESP = new LinkedList<>();
        //Collections.shuffle(list, new Random());
        displayQueueIterator(miQueue);
        miQueue.add("add1");
        displayQueueIterator(miQueue);
        miQueue.add("add2");
        displayQueueIterator(miQueue);
        miQueue.add("add3");
        displayQueueIterator(miQueue);
        miQueue.add("add4");
        displayQueueIterator(miQueue);
        miQueue.add("add5");
        displayQueueIterator(miQueue);
        miQueue.add("add6");
        displayQueueIterator(miQueue);
        miQueueRESP.addAll(miQueue);
        displayQueueIterator(miQueueRESP);
        displayQueueIterator( miQueue);

        System.out.println("miQueue.poll(): " + miQueue.poll());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.poll(): " + miQueue.poll());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.remove(): " + miQueue.remove());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.remove(): " + miQueue.remove());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.remove(): " + miQueue.remove());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.remove(): " + miQueue.remove());
        displayQueueIterator(miQueue);
        displayQueueIterator(miQueue);

        miQueue.clear();
        miQueue.addAll(miQueueRESP);
        displayQueueIterator(miQueue);
        System.out.println("miQueue.peek(): " + miQueue.peek());
        displayQueueIterator(miQueue);
        System.out.println("miQueue.poll(): " + miQueue.poll() );
        displayQueueIterator(miQueue);

        System.out.println( "miQueue.add(\"add1\"): "  + miQueue.add("add1"));  //add at last
        System.out.println( "miQueue.add(\"add2\"): "  + miQueue.add("add2"));  //add at last
        displayQueueIterator(miQueue);
        System.out.println( "miQueue.remove(2): " + miQueue.remove(2));
        System.out.println( "miQueue.remove(\"add2\")" + miQueue.remove("add2"));

        displayQueueIterator(miQueue);

        miQueue.clear();
        miQueue.addAll( miQueueRESP);
        displayQueueIterator(miQueue);
        displayQueueIterator(miQueueRESP);
        System.out.println( "miQueueRESP.containsAll( miQueue): " + miQueueRESP.containsAll( miQueue) );
        miQueue.add("EXTRA");
        displayQueueIterator(miQueue);
        displayQueueIterator(miQueueRESP);
        System.out.println( "miQueueRESP.containsAll( miQueue): " + miQueueRESP.containsAll( miQueue) );

    }

    private void displayQueueIterator(Queue queue) {
        System.out.print("size: " + queue.size() + " ");
        Iterator iterator = queue.iterator();
        while (iterator.hasNext()) {
            System.out.print( iterator.next() + ", ");
        }
        System.out.println();
    }

    private void displayQueueIntFor(Queue<Integer> queue) {
        System.out.print("size: " + queue.size() + " ");
        for ( int i = 0; i < queue.size(); i++) {
            System.out.print( "queue.get(i) NOT ENABLED");
        }
        System.out.println();
    }

    private void displayQueueStream(Queue queue) {
        System.out.print("size: " + queue.size() + " ");
        queue.stream().forEach(e -> System.out.print(e + ", "));
        System.out.println();
    }


}

SetLab

public class SetLab {
    public SetLab() {

        //int[] arrint = {1,4,2,5,7,11,12,75,23,76};
        Integer[] arrInt = {12,12,75,23,23,76,1,4,2,5,7,11,12,23};
        //HashSet<Integer> hashSet = new HashSet<>(Arrays.asList(1,4,2,5,7,11,12,75,23,76));
        HashSet<Integer> hashSet = new HashSet<>( Arrays.asList( arrInt));
        TreeSet<Integer> treeSet = new TreeSet<>( Arrays.asList( arrInt));

        System.out.print("ORIGINAL          : ");
        displayArr( arrInt);
        //displayIterator( hashSet);
        System.out.print("HashSet Sin Orden : ");
        displayFor( hashSet);
        System.out.print("TreeSet Con Orden : ");
        displayFor( treeSet);
        //displayForEach( hashSet);

        HashSet<Integer> hashSet2 = new HashSet<>();

        hashSet2.addAll( hashSet);

        System.out.println("hashSet2");
        displayFor( hashSet2);

        System.out.println("hashSet.equals(hashSet): " + hashSet.equals( hashSet));
        System.out.println("hashSet.equals(hashSet2): " + hashSet.equals( hashSet2));

        System.out.println("hashSet2.add( 11): " + hashSet2.add( 11));
        System.out.println("hashSet.equals(hashSet2): " + hashSet.equals( hashSet2));

        System.out.println("hashSet2.add( 99): " + hashSet2.add( 99));
        System.out.println("hashSet.equals(hashSet2): " + hashSet.equals( hashSet2));

        HashSet<Integer> hashSetResp = new HashSet<>( hashSet);
        HashSet<Integer> hashSet2Resp = new HashSet<>( hashSet2);
        displayFor( hashSetResp);
        displayFor( hashSet2Resp);

        System.out.println("hashSet.retainAll( hashSet2): " + hashSet.retainAll( hashSet2));
        System.out.println("hashSet2.retainAll( hashSet): " + hashSet2.retainAll( hashSet));

        hashSet.clear(); hashSet.addAll( hashSetResp);
        hashSet2.clear(); hashSet2.addAll( hashSet2Resp);

        System.out.println(hashSet2.removeAll( hashSet));
        displayFor(hashSet2);

        System.out.println("hashSet2.contains( 99): " + hashSet2.contains( 99));
        System.out.println("hashSet.contains( 99): " + hashSet.contains( 99));

        System.out.println( String.format("%3s", "2").replace(" ","0"));
        Set<String> set = new TreeSet<String>((o1, o2) ->  String.format("%3s", o1.substring( o1.indexOf(" ") + 1)).replace(" ","0")
                                         .compareTo(  String.format("%3s", o2.substring( o2.indexOf(" ") + 1)).replace(" ","0")
                                         ));
        //Set<String> set = new TreeSet<String>((o1, o2) ->  o1.substring( o1.indexOf(" ") + 1)
        //        .compareTo(  o2.substring( o2.indexOf(" ") + 1)));

        set.add("test 15");
        set.add("dfd 2");
        set.add("ersfd 20");
        set.add("asdt 10");
        set.stream().forEach(s -> System.out.println(s));


    }

    private void displayArr(Integer[] arrInt) {
        for (int i = 0; i < arrInt.length; i++){
           System.out.print( arrInt[i] + ", ");
        }
        System.out.print( "size: " + arrInt.length);
        System.out.println();
    }

    private void displayForEach(HashSet<Integer> hashSet) {
        hashSet.forEach(e -> System.out.print(e + ", ") );
        System.out.print( "size: " + hashSet.size());
        System.out.println();
    }

    private void displayFor(Set<Integer> set) {
        for( Integer e: set){
            System.out.print( e + ", ");
        }
        System.out.print( "size: " + set.size());
        System.out.println();
    }

    private void displayIterator(Set set) {
        Iterator iter = set.iterator();
        while ( iter.hasNext()){
            System.out.print( iter.next() + ", ");
        }
        System.out.print( "size: " + set.size());
        System.out.println();
    }
}

HashMapLab

public class HashMapLab {

    public HashMapLab() {
        HashMap<String, Integer> hashMapColor = new HashMap<>();

        String colores = "Rojo Naranga Amarillo Verde Azul Índigo Violeta";  //orden del arcoiris

        System.out.println(colores);
        StringTokenizer stringTokenizer = new StringTokenizer(colores);
        int i = 1;
        while (stringTokenizer.hasMoreTokens()) {
            hashMapColor.put(stringTokenizer.nextToken(), new Integer(i++));
        }

        //display hashMap
        hashMapColor.entrySet().stream()
                .map(s -> String.format("|%" + 10 + "s|", s))
                .forEach(s -> System.out.print(s));
        System.out.println();

        //display hashMap using BiConsumer
        hashMapColor.forEach((k, v) -> System.out.print(String.format("|%" + 10 + "s", k) + ":" + v + "|"));
        System.out.println();

        // TreeMap (alphabetic order) Order)
        System.out.println("TreeMap");
        Map<String, Integer> alphaOrderColor = new TreeMap<>();
        stringTokenizer = new StringTokenizer(colores);
        i = 1;
        while (stringTokenizer.hasMoreTokens()) {
            alphaOrderColor.put(stringTokenizer.nextToken(), new Integer(i++));
        }

        alphaOrderColor.forEach((k, v) -> System.out.print(String.format("|%" + 10 + "s", k) + ":" + v + "|"));
        System.out.println();

        System.out.println("TreeMap order without accent");
        Map<String, Integer> alphawithoutAccentOrderColor = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return removeAccents(o1).compareTo(removeAccents(o2));
            }
        });

        stringTokenizer = new StringTokenizer(colores);
        i = 1;
        while (stringTokenizer.hasMoreTokens()) {
            alphawithoutAccentOrderColor.put(stringTokenizer.nextToken(), new Integer(i++));
        }

        alphawithoutAccentOrderColor.forEach((k, v) -> System.out.print(String.format("|%" + 10 + "s", k) + ":" + v + "|"));
        System.out.println();

        // lambda y constructor TreeMap
        System.out.println("TreeMap order without accent Lambda in TreeMap constructor");
        Map<String, Integer> valueOrderLambdaColor = new TreeMap<>((o1, o2) -> removeAccents(o1).compareTo(o2));
        //Map<String, Integer> valueOrderLambdaColor = new TreeMap<>((o1, o2) -> o2.compareTo(o1));
        stringTokenizer = new StringTokenizer(colores);
        i = 1;
        while (stringTokenizer.hasMoreTokens()) {
            valueOrderLambdaColor.put(stringTokenizer.nextToken(), new Integer(i++));
        }

        valueOrderLambdaColor.forEach((k, v) -> System.out.print(String.format("|%" + 10 + "s", k) + ":" + v + "|"));
        System.out.println();

        List<Map.Entry<String, Integer>> listSortbyValue;
        System.out.println("Map sorted by Value");
        listSortbyValue = sortMapByValue(valueOrderLambdaColor);
        listSortbyValue.stream().forEach(e -> System.out.print(String.format("|%" + 10 + "s", e.getKey()) + ":" + e.getValue() + "|"));

        Map<String, List<String>> sinonimos = new TreeMap<>();

/*
        witty "amusing, humorous, funny, clever, facetious, smart, entertaining, whimsical, jokey, jocular, droll, comedic"
        joker "comic, clown, comedian, funnyman"
        slum "ghetto , hood (Slang), skid row, shanty town, the wrong side of the tracks (informal), poor neighborhood"
                sloopy "disordered, disorderly, cluttered, disarranged, unkempt, disheveled"
        stink "stench , reek, funk , odor, odour (UK), smell , bad smell, bad odor"

        preclude "prevent , stave off, head off, ward off, avert , avoid , negate, neutralize"
        nuance "subtlety, distinction , difference , fine point, shade"
        weild "exercise , exert , apply , ply, use , effect , command , control , manage"
        fate "luck , chance , fortune , happenstance (mainly US), good luck, bad luck, misfortune, good fortune, bad fortune"
                apalled shock , amaze, horrify, dismay , surprise , disgust, offend, cause offense
        cripping disabled person, handicapped person (dated), the handicapped (dated), the disabled, amputee, paraplegic
                tenant renter, lessee, rent payer, lodger, boarder, leaseholder, holder
        rift fissure, split , crack , break , fracture, hole , tear , gap
                hail barrage , torrent, deluge, shower , salvo, volley, battery
        relay communicate , pass on, pass along, convey , send , deliver , forward , transmit, transfer , circulate


    squeaking squeal , shrill sound, shrill cry, narrow escape
    wee small , tiny , infinitesimal, little , minute , negligible
        screech shriek , yell , outcry , cry , scream , howl , wail

    swooping plunge , fall , drop , descent , dive , chute, slide
    warfare combat, war , conflict , armed conflict, hostilities, fighting
    meek subdued , weak , yielding, docile, submissive, compliant , resigned
    invoice bill , itemized bill, tab (informal), request for payment, bill of account
    relinquish give up, surrender , give away, renounce, abandon , waive , hand over, get rid of, shed
*/

    }

    private List<Map.Entry<String, Integer>> sortMapByValue(Map<String, Integer> map) {
        List<Map.Entry<String, Integer>> elements = new LinkedList<>( map.entrySet());
        Collections.sort( elements, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        return elements;
    }

    private Map<String, Integer> countWords( List<String> words) {
        Map<String, Integer> mapWordCount = new TreeMap<>();
        for (String word: words) {
            if ( mapWordCount.containsKey( word)){
                int count = mapWordCount.get(word) + 1;
                mapWordCount.put( word, count);
            } else {
                mapWordCount.put( word, 1);
            }
        }
        return mapWordCount;
    }

    public  static String removeAccents(String text) {
        return text == null ? null : Normalizer.normalize(text, Normalizer.Form.NFD)
                .replaceAll("\\p{InCOMBINING_DIACRITICAL_MARKS}+","");
    }

    private void displayKVformatted(String k, Integer v) {
        String str = String.format("%" + 10 + "s", k);
        System.out.println( str + " " + v);
    }

    //System.out.print( String.format("|%" + 10 + "k|", k.toString()) + " " + v)
}

StreamLab


public class StreamLab {
    public StreamLab() {

        //reduceStreamMayor();
        reductions();
    }

    private void reductions() {

/*   https://www.logicbig.com/tutorials/core-java-tutorial/java-util-stream/reduction.html
    Returns
       Single Value:   min(), max(),  count(), sum(),  average(), summaryStatistics()
       Collections:    collect(), toArray()

       fold operations uses binary function ( accumulator ) whose first argument is the
       value returned from the last excecution of the same function, second argunent is the
       current stream element
       (a, b) ->
       a previos result, b current element of the stream

       BiFunction
          |
       BinaryOperator
 */
        // (1) Optional<T>  reduce( BinaryOperator<T> accumulator)

        int i = IntStream.range(1, 6)
                .reduce((a, b) -> a * b)
                .orElse(-1);
        System.out.println("product:" + i);

        i = IntStream.range(1, 6).sum();
        System.out.println("sum:" + i);

        // (2) T reduce ( T Identity, BunaryOperator<T> accumulator)
        // Identity is the initial value of reduction
        i = IntStream.range(1, 6)
                .reduce(100, (a, b) -> a * b);
        System.out.println("product with initial value of 100: " + i);

        i = IntStream.empty()
                .reduce(100, (a, b) -> a * b);
        System.out.println("product with initial value of 100 with empty stream: " + i);

        i = IntStream.range(1, 6)
                .parallel()
                .reduce(100, (a, b) -> a * b);
        System.out.println("product with initial value of 100 paralelized (identity taken many times (wrong answer)): " + i);

        //(3) <U> U reduce(U identity,
        //                 Bifunction<U, ? super T,U> accumulator,
        //                 BinaryOperator<U> combiner)
        //  this is a combination of map() and reduce()
        // the identity value must be an identity for the combiner function
        // combiner(identity, u) == u
        // also combiner must be compatible with accumulator
        // combiner.apply( u, accumulator.apply( identity, t)) == accumulator.apply( u, t)

        i = Stream.of("2","3","4","5")     // using anonymous classes
                .parallel()
                .reduce(0, new BiFunction<Integer, String, Integer>() {
                    @Override
                    public Integer apply(Integer integer, String s) {
                        return Integer.sum(integer, Integer.parseInt(s));
                    }
                }, new BinaryOperator<Integer>() {
                    @Override
                    public Integer apply(Integer integer, Integer integer2) {
                        return Integer.sum( integer, integer2);
                    }
                });
        System.out.println("string values converted and sumed: " +  i );

        i = Stream.of("2","3","4","5")     // using anonymous classes
                .parallel()
                .reduce( 0, ( integer, s) -> Integer.sum(integer, Integer.parseInt( s )),
                        ((integer, integer2) -> Integer.sum( integer, integer2)));
        System.out.println("string values converted and sumed: " +  i );

        // Stream min()
        // Optional<T> min( Comparator<? super T> comparator)

        String miStr = Stream.of("Perro","zanahoria","caballo")
                    .min(String::compareTo)
                    .get();
        System.out.println(miStr);

        miStr = Stream.of("Perro","zanahoria","caballo")
                .filter(e -> e.length() == 3)
                .min(String::compareTo)
                .orElse("Ninguno");
        System.out.println(miStr);

        Optional<String> miReduce = Stream.of("Perro","zanahoria","caballo")
                .reduce( (s, s2) -> s.compareTo(s2) <= 0 ? s : s2);
        System.out.println(miReduce);

         miStr = Stream.of("Perro","zanahoria","caballo")
                .max(String::compareTo)
                .get();
        System.out.println(miStr);

        miReduce = Stream.of("Perro","zanahoria","caballo")
                .reduce((s,s2)-> s.compareTo(s2) > 0 ? s :s2);
        System.out.println(miStr);

        double midouble = DoubleStream.of( 1.3, 2.5, 3, 5.4)
                .sum();
        System.out.println(midouble);

        midouble = DoubleStream.of(1.3, 2.5, 3, 5.4)
                .reduce( 0 , Double::sum);
        System.out.println(midouble);

        double average = LongStream.range(1, 10)
                .average()
                .orElse(-1);
        System.out.println( average);

        long micount = Stream.of("Perro","zanahoria","caballo")
                .count();
        System.out.println( micount);

        micount = Stream.of("Perro","zanahoria","caballo")
                .mapToLong( s -> 1L)
                .sum();

        System.out.println( micount);

        IntSummaryStatistics miStat = IntStream.rangeClosed(1,10)
                .summaryStatistics();
        System.out.println(miStat);


    }

    private void reduceStreamMayor() {
        //List<String> words = new ArrayList<>();   // If we want it Empty
        List<String> words = Arrays.asList("Esta","es","una","prueba","para","obtener","la","palabra","mayor","o","menor");

        System.out.println(words.toString());

        Optional<String> longestWord = words.stream()
                .reduce( (word1, word2 )-> word1.length() > word2.length() ? word1 : word2);
        System.out.println( "longestWord: " + longestWord);

        Optional<String> shortestWord = words.stream()
                .reduce( ( word1, word2) -> word1.length() < word2.length() ? word1 : word2);
        System.out.println( "shortestWord: " + shortestWord);
        if (shortestWord.isPresent()) System.out.println(shortestWord.get());

        // Array <- list
        String[] arrString = new String[ words.size() ];
        arrString = words.toArray( arrString );
        Arrays.stream( arrString).forEach(a-> System.out.print(a + " "));
        //String[] arrString = {"Esta","es","una","prueba","para","obtener","la","palabra","mayor","o","menor"};

        Optional<String> joinedWords = Arrays.stream( arrString)
                .reduce( (word1, word2) -> word1 + "-" + word2 );
        if ( joinedWords.isPresent()) {
            System.out.println( joinedWords.get());
        }

        // Stream reduce sum a list of integers
        Integer[] arrInt = {-2, 0, 200, 12, 23, -45};

        List<Integer> listInt = new ArrayList<>( Arrays.asList( arrInt));
        listInt.stream().forEach( e -> System.out.print(e + " "));
        System.out.println();

        Optional<Integer> sumArrInt = Arrays.stream( arrInt)   // arrInt to stream.reduce
                .reduce( (a, b) -> a + b);
        if ( sumArrInt.isPresent()) {
            System.out.println( "sumArrInt: " + sumArrInt );
        }

        LongStream.range( 2,10).forEach(a-> System.out.print(a + " "));  // LongStream.range  reduce   .orElse exclude the right most element
        long product = LongStream.range( 2, 10)
                .reduce( (a, b) -> a * b)
                .orElse(-1);
        System.out.println("product: " + product );

        LongStream.range( 2,10).forEach(a-> System.out.print(a + " "));  // LongStream.range  reduce   .orElse exclude the right most element
        long sumaA = LongStream.range( 2, 10)
                .reduce( (a, b) -> a + b).getAsLong();
                //.orElse(-1);
        System.out.println("sumaA: " + sumaA );

        long sumaB = LongStream.of(1L, 1L, 1L, 1L, 1L)
                .reduce( (a, b) -> a + b)
                .orElse( -1);
        //.orElse(-1);
        System.out.println("sumaB: " + sumaB );  // sumaB: 5


    }
}


eot

No hay comentarios:

Publicar un comentario