Friday, May 18, 2018

java special for collection size, array size, and string size


Size:
For Collections (eg: Map, List, etc ): usually it use collection.size(),
eg
        Map<Character, Integer> map = new HashMap<>();
        int s1 = map.size();
   
        List<Integer> list = Arrays.asList(a);
    int s2 = list.size();

But For Array, it uses length,
eg
        Integer[] array = new Integer[10];
        int s3 = array.length;


For String, it uses length(),

        String str = "string";
        int s4 = str.length();

Tuesday, April 3, 2018

vanilla-template

vanilla-template

A simple vanilla template. With just the bare minimum to jump start a project

Sunday, March 25, 2018

v2mom - Vision, Values, Methods, Obstacles and Measures



https://sliwinski.com/v2mom/
https://trailhead.salesforce.com/en/modules/manage_the_sfdc_organizational_alignment_v2mom/units/msfw_oav2m_writing_a_v2mom


V2MOM stands for Vision, Values, Methods, Obstacles and Measures



The vision helped us define what we wanted to do.
  • In 1-3 sentences, what do you want to accomplish? What impact will it have?
  • Keep it simple and inspiring.


The values established what was most important about that vision; it set the principles and beliefs that guided it (in priority). 

  • What 3 values are important as you pursue your vision? 
  • Values guide everyday decisions and tradeoffs.

The methods illustrated how we would get the job done by outlining the actions and the steps that everyone needed to take. 

  • What 4-8 things do you want to accomplish? 
  • Which are most important to you? 
  • Do they align with the Company V2MOM? 
  • Do they align with your manager’s?



The obstacles identified the challenges, problems, and issues we would have to overcome to achieve our vision. 
  • What is going to make accomplishing all of this diffcult?

The measures specified the actual result we aimed to achieve; often this was defined as a numerical outcome.

  • For each Method, how will you know you’ve been successful? 
  • Focus on the measurable outcomes versus activities. 
  • Can be quantified or quantitative?



How to Write a V2MOM?
https://trailhead.salesforce.com/en/modules/manage_the_sfdc_organizational_alignment_v2mom/units/msfw_oav2m_writing_a_v2mom

VisionThe Vision represents what you want to achieve or accomplish. It focuses on what’s most important to you. Writing a great Vision helps you paint a picture of what you want the future to look like.

“Global leadership in providing the software as a service model driven by an enthusiastic and wildly successful customer community, and energized by world-class employees.” Each year, we create a new Vision that boldly describes what we are trying to accomplish. And every function, team, manager and employee does the same.

What is your bold Vision for what you want to achieve this year?
When writing your Vision, think about:
  • What you want to accomplish? (Keep it to 1-3 sentences)
  • What impact will it have on your company, employees, customers, and community?
  • How can make it inspiring, fun, and creative (it can and should be a reflection of you!)?

ValuesValues represent the principles or beliefs that are most important as you pursue your Vision. They guide everyday decisions and tradeoffs.

The very first V2MOM at Salesforce included Values like “world class organization,” “time to market,” and “usability.” Now, our business Values includes words like “trust,” “growth,” and “innovation.”

Which Values come to mind when thinking about the principles needed to achieve your Vision? When writing about your Values, consider:
  • Which three Values are most important as you pursue your Vision?
  • How can you describe those Values so that everyone is clear on what it means to live them?
  • How will these Values guide your everyday decisions and tradeoffs?


Methods
Methods represent the actions you take to achieve your Vision.
For a company or team, methods are the steps to take to bring the vision to reality. For Salesforce, some of the initial Methods that Marc Benioff and his co-founders scrawled on the back of that envelope were to hire the team, rapidly develop the product, and build partnerships—all critical steps to achieve our initial Vision.
What are the specific actions that your company or team needs to take to achieve the Vision?
As you write out your Methods:
  • Think carefully about what actions you need to take to achieve your Vision
  • What 5–8 things do you want to accomplish?
  • Do your Methods align to the corporate V2MOM? Your manager’s V2MOM?
  • Prioritize the order of your Methods with the highest priority Method at the top
  • Keep your writing simple and inspiring


Obstacles
Obstacles are things that block your progress, get in your way, or make it difficult to accomplish what you’ve outlined. Identifying Obstacles before you jump into your work helps you anticipate challenges and proactively consider how to overcome them.
What are the most pressing Obstacles you can think of that will get in the way of achieving your Vision? How might you overcome them? When writing your Obstacles, think about:
  • What’s going to make accomplishing your vision and executing your Methods difficult?
  • What do you need to be mindful of to overcome your Obstacles?
  • What specifically can you do to overcome your Obstacles?

Measures
Measures tell you and others when you’ve achieved success or successfully completed your Methods. They focus on the measurable outcomes of your work, not your day-to-day activities. It’s really the ”brass tacks” of it all. A wise V2MOM sage once said, “If you’re not able to measure it, you probably don’t understand what you are trying to achieve.”
or each of your Measures, how can you clearly define success? When writing your Measures:
  • Think about how you know when you’ve been successful.
  • Focus on the measurable outcomes, for example “80% of managers rated as highly effective.”
  • Make the measures SMART. Not sure what that means? Read on!



Writing SMART Measures

SMART is an acronym that helps you think through all the elements of establishing clear, actionable, and measurable Measures. When writing your V2MOM Measures, make sure they follow the SMART format.





S - specificSpecific - Clearly define your focus and what you’re going to do.
M - measurableMeasurable - Quantify an indicator of progress, such as percentages, numbers, targets.
A - achievableAchievable - Set the bar high, yet make it achievable.
R - relevantRelevant - Ensure that the Measure supports the company’s and your manager’s V2MOM Measures.
T - timelyTimely - Set a specific and reasonable time frame for completion.

Want a little more clarity on what SMART looks like?
SMART Measures Look Like ThisNot This
Achieve market share of 30% in the United States by the end of the fiscal year.Dominate the U.S. market!
Be rated in the top 3 in Gartner’s Healthcare Magic Quadrant and Forrester’s Healthcare Wave by the end of the fiscal year.Lead the market direction and shape the evolution of the Healthcare market.
Achieve a top 30 ranking on Fortune’s 2017 Best Companies to Work For list.Be a Great Place to Work.
At Salesforce, we offer our employees two options for writing their Measures.
  1. Progress Measures: Setting a target number or percentage, for example “Achieve a 75% open rate for customer email campaigns by the end of Q2.”
  2. Completion Measures: Setting a goal of whether or not a particular activity is completed, such as “Launch a blog for internal communications by the end of Q4.”

Tips for Writing Your V2MOM


Do ThisWhich Looks Like This
Keep it shortThink CliffsNotes, not War and Peace. Make your statements focused. If your V2MOM is too long, it’s likely not focused.
Choose your words wiselyWords make a difference. For example, you can “empower” users through support or you can ”enable” users with tools.
List your priorities in orderOrder your Values, Methods, and Measures in priority order to show their importance. When using your V2MOM to guide decisions, the priority is key.
Make it your ownDon’t copy and paste. No two V2MOMs should be the same. Every individual in the organization should have their own Vision and Goals.























Sunday, March 18, 2018

Java 8 consumer chaining


https://www.javabrahman.com/java-8/java-8-java-util-function-consumer-tutorial-with-examples/

Consumer => accept(T t)
Consumer interface will accept some Type T, and do something on it.

import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

public class ConsumerFunctionExample{
    public static void main(String args[]){
        Consumer<Integer> consumer = i-> System.out.print(" "+i);
        Consumer<Integer> consumerWithAndThen = consumer.andThen( i-> System.out.print("(printed "+i+")"));
        //  Note:
        //      i-> System.out.print("(printed "+i+")") will create a new Consumer Object, and it can be
        //      cosidered as: Consumer<Integer> consumer2 =  i-> System.out.print("(printed "+i+")")
        //      and comsumer2 will be pass to consumer.andThen()
        //      Because consumer addnThen returns another Consumer<T> object
        //        public interface Consumer<T> {
        //            void accept(T t);
        //            default Consumer<T> andThen(Consumer<? super T> after) {
        //                Objects.requireNonNull(after);
        //                return (T t) -> { accept(t); after.accept(t); };
        //            }
        //        }
        //      In this case (T t) -> { accept(t); after.accept(t); };
        //      New consumer created new accept function which include 2 operations
        //                { consumer.accept(t); consumer.andThen();}
        //                => { i-> System.out.print(" "+i), i-> System.out.print("(printed "+i+")")}

        System.out.println(consumer.hashCode());
        System.out.println(consumerWithAndThen.hashCode());
        System.out.println(consumer == consumerWithAndThen);
        List<Integer> integerList= Arrays.asList(new Integer(1),
                new Integer(10), new Integer(200),
                new Integer(101), new Integer(-10),
                new Integer(0));
        printList(integerList,consumerWithAndThen);
        System.out.println();


        // **********   Consumer Chaining  *********
        Consumer<String> consumer1 = i -> System.out.println(i);

        // Note: consumer2.accept = {consumer1.accept + consumer1.andThen}
        //       and:
        //       cosumer1.accept = i -> System.out.println(i)
        //       cosumer1.andThen = i -> System.out.println("length:" + i.length())
        Consumer<String> consumer2 = consumer1.andThen(i -> System.out.println("length:" + i.length()));

        // Note: consumer3.accept = {consumer2.accept + consumer2.andThen}
        //       and:
        //       cosumer2.accept = {consumer1.accept + consumer1.andThen}
        //       cosumer2.andThen = i -> System.out.println("Lower Case:" + i.toLowerCase()))
        Consumer<String> consumer3 = consumer2.andThen(i -> System.out.println("Lower Case:" + i.toLowerCase()));

        // Note: consumer4.accept = {consumer3.accept + consumer3.andThen}
        //       and:
        //       cosumer3.accept = {consumer2.accept + consumer2.andThen}
        //       cosumer3.andThen = i -> System.out.println("Upper Case:" + i.toUpperCase()))
        Consumer<String> consumer4 = consumer3.andThen(i -> System.out.println("Upper Case:" + i.toUpperCase()));


        // Note: consumer4.accept will call the followings: { consumer3.accept + consumer3.andThen }
        //       consumer3.accept + consumer3.andThen
        //   =>  consumer3.accept + i -> System.out.println("Upper Case:" + i.toUpperCase()))
        //   =>  {consumer2.accept + consumer2.andThen}
        //       + i -> System.out.println("Upper Case:" + i.toUpperCase()))
        //   =>  {consumer1.accept + consumer1.andThen}
        //       + i -> System.out.println("Lower Case:" + i.toLowerCase()))       //  cosumer2.andThen
        //       + i -> System.out.println("Upper Case:" + i.toUpperCase()))       //  cosumer3.andThen
        //   =>  i -> System.out.println(i)                                        //  cosumer1.accept
        //       + i -> System.out.println("length:" + i.length())                 //  cosumer1.andThen
        //       + i -> System.out.println("Lower Case:" + i.toLowerCase()))       //  cosumer2.andThen
        //       + i -> System.out.println("Upper Case:" + i.toUpperCase()))       //  cosumer3.andThen
        consumer4.accept("Andy");

    }
    public static void printList(List<Integer> listOfIntegers, Consumer<Integer> consumer){
        for(Integer integer:listOfIntegers){
            consumer.accept(integer);
        }
    }
}

Sunday, March 11, 2018

Java Stack, Queue(Deque), PriorityQueue



import com.sun.jmx.remote.internal.ArrayQueue;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;


public class Test {

    public static void main(String [] args) {
        testStack();
        testQueue();
        testPriorityQueue();
    }

    public static void testStack() {
        System.out.println("------- test stack -------");
        Stack<Integer> s = new Stack<Integer>();
        s.push(1);
        s.push(2);
        s.push(3);
        s.push(4);

        System.out.println(s);
        System.out.println("s.peek: " + s.peek());

        s.pop();
        System.out.println(s);


        System.out.println("s.peek: " + s.peek());
        System.out.println(s);


        s.pop();
        System.out.println(s);


        s.pop();
        System.out.println(s);


        s.pop();
        System.out.println(s);

        try {
            s.pop();
            System.out.println(s);
        } catch (EmptyStackException ex) {
            System.out.println("exception: " + ex.getMessage());
        }

    }

    public static void testQueue() {
        System.out.println("------- test queue -------");

        Queue<Integer> q = new ArrayDeque<>();
        q.add(1);
        q.add(2);
        q.add(3);
        q.add(4);
        System.out.println(q);

        while(!q.isEmpty()) {
//            System.out.println(q.peek());            Integer removed = q.remove();
            System.out.println("removed: " + removed);
            System.out.println(q);
        }
    }

    public static void testPriorityQueue() {
        System.out.println("------- test queue -------");

        PriorityQueue<Integer> pq = new PriorityQueue<>();
        pq.add(5);
        pq.add(2);
        pq.add(1);
        pq.add(4);
        pq.add(3);

        System.out.println(pq);

        while(!pq.isEmpty()) {
            System.out.println("pq top: " + pq.peek());
            pq.poll();
            System.out.println("pq: " + pq);
        }
    }
}

Java properties


https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html

Java properties implements a map that can be easily saved and loaded using a plain text.


import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;


public class Test {

    public static void main(String [] args) {
        testProperties();
    }


    /*        The followings generate the followings:        #This is a comment        #Sun Mar 11 15:42:13 PDT 2018        passwd=password        username=admin    * */    public static void testProperties() {
        createProperties();
        Properties settings = readProperties();

        /*        *  output:            {passwd=password, username=admin}            admin            password            null            null        * */        System.out.println(settings);
        System.out.println(settings.getProperty("username"));
        System.out.println(settings.getProperty("passwd"));
        System.out.println(settings.getProperty("password"));
        System.out.println(settings.getProperty("user"));

    }

    static void createProperties() {
        String fname = "settings.properties";
        Path path = FileSystems.getDefault().getPath("./"+ fname).toAbsolutePath();
        Properties settings = new Properties();
        settings.put("username", "admin");
        settings.put("passwd", "password");

        try(OutputStream out = Files.newOutputStream(path)) {
            settings.store(out, "This is a comment");
        } catch (java.io.IOException ex) {
            System.out.println("IOException: " + ex.getMessage());
        } catch (Exception ex) {
            System.out.println("Exception: " + ex.getMessage());
        }
    }

    static Properties readProperties() {
        String fname = "settings.properties";
        Path path = FileSystems.getDefault().getPath("./"+ fname).toAbsolutePath();
        Properties settings = new Properties();

        try(InputStream in = Files.newInputStream(path)) {
            settings.load(in);
        } catch (java.io.IOException ex) {
            System.out.println("IOException: " + ex.getMessage());
        } catch (Exception ex) {
            System.out.println("Exception: " + ex.getMessage());
        }

        return settings;
    }

}

Java Set



import java.util.*;


public class Test {

    public static void main(String [] args) {
        testHashSetIterator();
    }



    public static void testHashSetIterator() {
        Set<Integer> set = new HashSet<>();
        set.add(1);
        set.add(1);
        set.add(1);
        set.add(1);
        set.add(2);
        set.add(2);
        System.out.println("set size: " + set.size());
        System.out.println(set);
        System.out.println("set remove 1 " );
        set.remove(1);
        System.out.println(set);

        System.out.println("set contains 1: " + set.contains(1));
        System.out.println(set);

        set.remove(1);
        set.remove(2);
        set.remove(1);
        set.remove(2);
        set.remove(1);
        set.remove(2);
        System.out.println(set);

        // sorted set: treeset        Set<Integer> sortedSet = new TreeSet<>();
        sortedSet.add(3);
        sortedSet.add(4);
        sortedSet.add(6);
        sortedSet.add(2);
        sortedSet.add(3);
        sortedSet.add(4);
        sortedSet.add(2);
        sortedSet.add(1);
        sortedSet.add(3);
        sortedSet.add(5);
        sortedSet.add(6);
        System.out.println("sortedSet size: " + sortedSet.size());
        System.out.println(sortedSet);
        System.out.println("sortedSet remove 1 " );
        sortedSet.remove(1);
        System.out.println(sortedSet);

        System.out.println("sortedSet contains 1: " + sortedSet.contains(1));
        System.out.println(sortedSet);

        sortedSet.remove(1);
        sortedSet.remove(2);
        sortedSet.remove(1);
        sortedSet.remove(2);
        sortedSet.remove(1);
        sortedSet.remove(2);
        System.out.println(sortedSet);

    }


}

Java map



import java.util.*;


public class Test {

    public static void main(String [] args) {
        testHashMapIterator();
    }



    public static void testHashMapIterator() {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(1, 500);
        map.put(1, 100);
        map.put(3, 300);
        map.put(2, 200);

        System.out.println("map size: " + map.size());
        System.out.println(map);

        System.out.println("map contains 1: " + map.containsKey(1));
        System.out.println("map remove 1 " );
        map.remove(1);
        System.out.println(map);
        System.out.println("map contains 1: " + map.containsKey(1));

        // iterate by map entry        System.out.println("Iterate by map entry:");
        for(Map.Entry<Integer, Integer> entry: map.entrySet()) {
            System.out.println("entry: key: "+ entry.getKey() + ", value:" + entry.getValue());
        }

        // iterate by map keys        System.out.println("Iterate by map keyset:");
        for(Integer key: map.keySet()) {
            System.out.println("entry: key: "+ key + ", value:" + map.get(key));
        }

        // iterate by map values        System.out.println("Iterate by map valueset:");
        for(Integer value: map.values()) {
            System.out.println("entry: value: "+ value);
        }

        System.out.println("map contains 5: " + map.containsKey(5));
        System.out.println("map remove 5 " );
        map.remove(5);
        System.out.println(map);
        System.out.println("map contains 5: " + map.containsKey(5));



        System.out.println("map contains value 200: " + map.containsValue(200));
        System.out.println(map);
        map.remove(2, 200);
        System.out.println("map contains value 200: " + map.containsValue(200));
        System.out.println(map);

        // Note: the followings iterate the map; very slow        // remove value 300        map.values().remove(300);

        System.out.println("map contains 2: " + map.containsKey(2));
        System.out.println(map);

        map.remove(1);
        map.remove(2);
        map.remove(1);
        map.remove(2);
        map.remove(1);
        map.remove(2);
        System.out.println(map);

        // sorted map: TreeMap is sorted based on the order of keys        Map<Integer, Integer> sortedMap = new TreeMap<>();

    }


}

Java vector




https://docs.oracle.com/javase/7/docs/api/java/util/Vector.html
https://docs.oracle.com/javase/7/docs/

import java.util.*;


public class Test {

    public static void main(String [] args) {
        testVectorIterator();
    }



    public static void testVectorIterator() {


        // initialize the vector with capacity with 8        List<Integer> vector = new Vector<>(3);

        // element will be added to vector at pre allocated places        vector.add(0, 1);
        vector.add(1, 2);
        vector.add(2, 3);

        // now vector will be expanded to add new element        vector.add(3, 4);
        vector.add(4, 5);


        System.out.println("vector size: " + vector.size());
        printCollection(vector);

        System.out.println("vector swap at position 0 and position 2 ");
        Collections.swap(vector, 0, 2);
        printCollection(vector);

        System.out.println("------------------------------------");

        System.out.println("vector sub vector between position 0 and position 2:");
        List subVector = vector.subList(0, 2);
        System.out.println("subVector class:" + subVector.getClass());
        System.out.println("subVector size:" + subVector.size());
        printCollection(subVector);

        // note: subvector only reference the position of vector        //       if vector value changed at postion 0 or positon 1 or else, subvector will change        //       because subvector always points to vector elements at postion [0, 2]        vector.set(0, 567);
        vector.set(1, 789);

        printCollection(subVector);


        System.out.println("------------------------------------");
        System.out.println("vector reverse:");
        Collections.reverse(vector);
        printCollection(vector);
        //subvector still points the vector position [0, 2]        printCollection(subVector);


        System.out.println("------------------------------------");

        Iterator it = vector.iterator();
        while(it.hasNext()) {
            Integer i = (Integer) it.next();
            it.remove();
        }
        System.out.println("After remove all elements in vector; vector size: " + vector.size());
        printCollection(vector);


        System.out.println("------------------------------------");
        List<Integer> vector2 = new Vector<>();
        vector2.add(7);
        vector2.add(7);
        vector2.add(7);
        vector2.add(8);
        vector2.add(8);
        vector2.add(9);

        System.out.println("vector2 size: " + vector2.size());
        printCollection(vector2);

        System.out.println("vector and vector2 disjoint: " + Collections.disjoint(vector, vector2));
        System.out.println("vector2 7 frequency: " + Collections.frequency(vector2, 7));
        System.out.println("vector2 9 frequency: " + Collections.frequency(vector2, 9));




    }


    // <T> must be declared before void to indicate compiler this is a generic method    static <T> void printCollection(Collection<T> c) {
        StringBuilder sb = new StringBuilder();
        for(Iterator it = c.iterator(); it.hasNext(); ){
            sb.append(it.next() + " -> ");
        }
        System.out.println(sb.toString());

        // or        // for(T t : c ){        //    sb.append(c);        // }        // System.out.println(sb.toString());    }
}

Java Iterator and List Iterator



https://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html
https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html
https://en.wikipedia.org/wiki/Java_collections_framework
https://beginnersbook.com/2014/06/listiterator-in-java-with-examples/
https://beginnersbook.com/2014/07/java-hashmap-iterator-example/

public class Test {

    public static void main(String [] args) {
        testIterator();
    }



    public static void testIterator() {


        // Create list [1, 2, 3]        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);


        printCollection(list);

        // Note iterator does not point to any element in the collection        // it is always between two elements, or it is before the first element, or after the last element        // So, when list.iterator() get called, iterator will be located before the first element        //   [it (Noref)| 1 | 2 | 3 ]        Iterator<Integer> it = list.iterator();


        // when it.remove() called, it will remove the element before it        // this will throws runtime exception java.lang.IllegalStateException,        // because there is no element before iterator it        // it.remove();
        // Every time it.next get called, iterator it will move to next element        //   [1 | it(ref position at value 1) | 2 | 3 ]        //it.next();
        printCollection(list);

//        while(it.hasNext()) {//            Integer i = it.next();//            System.out.println("i: "+ i);////            //it.remove();//        }
        // ListIterator has more rich functionalities        // ListIterator lit should be at beginning of the list        ListIterator<Integer> lit = list.listIterator();

        // lit.previousIndex() should be return -1, since lit is at the beginning of the list        System.out.println("lit.previousIndex(): " + lit.previousIndex());
        // lit.nextIndex() should be return 0, since lit is at the beginning of the list        System.out.println("lit.nextIndex(): " + lit.nextIndex());


        // [lit (no ref)| 1 | 2 | 3]        // when lit.set(999) called, lit will set the element it referenced        // Here if we cal lt.set(999) directly, it will fail        // this will throws java.lang.IllegalStateException, since there is no element before it        //lit.set(999);
        System.out.println("lit.previousIndex(): " + lit.previousIndex());
        System.out.println("lit.nextIndex(): " + lit.nextIndex());

        // we can add 1 element to lit        // [888| lit (no ref)| 1 | 2 | 3]        lit.add(888);
        printCollection(list);

        System.out.println("lit.previousIndex(): " + lit.previousIndex());
        System.out.println("lit.nextIndex(): " + lit.nextIndex());

        // If we use lit to set element 888 value directly, it will fail(Throw IllegalStateException)        // To use lit.set, it must by be referenced by next() or previous() first        // previous        // [ lit(ref position at value 888)| 888| 1 | 2 | 3]
        lit.previous();
        lit.set(22);
        // [ lit(ref position at value 22)| 22| 1 | 2 | 3]        printCollection(list);

        lit.set(999);
        // [ lit(ref position at value 999)| 999| 1 | 2 | 3]        printCollection(list);



        // [ lit(ref position at value 999)| 999| 1 | 2 | 3]        // [ lit2(no ref) | 999| 1 | 2 | 3 ]        ListIterator<Integer> lit2 = list.listIterator();

        // similar to set, lit.remove() must reference some position, before it get called        // only next and previous can initialize this kind of reference        // eg. the followings will fail//        lit2.remove();//        printCollection(list);
        // To make remove work, we need to let lit2 to reference a position        lit2.next();
        // Now lit2 reference the element of the list        // [ 999 | lit2(ref position at value 000)| 1 | 2 | 3]        // now we call list2.remove()        // it will remove 999, the reference to nothing,        // and if any other iterator reference to 999, the refernce will be marked as null        //        lit2.remove();
        printCollection(list);
        // [ lit2(no ref)| 1 | 2 | 3]

        // After lit2 remove 999        // Now lit becomes orphan ?? because it next 999 is gone?        // lit next is null        // before lit2 remove: [ lit(ref position at value 999)| 999| 1 | 2 | 3]        // after: [ lit(no ref) (ref position at value 999)| 999] lit doest not know where is 999's next        // since it's not in list any more????        // lit.next();   //<----- fail [ lit(no ref) (ref position at value 999)| 999]

        // to make it work we need make sure lit is not dangling anymore        // To make it work we need to set lit to list.iterator()        // [ lit(no ref)| 1 | 2 | 3]        lit = list.listIterator();


        // [ 100 | lit| 1 | 2 | 3]        lit.add(100);

        // Add one element at position lit, since lit is at the beginning of the list,        // so the new element will become the first element of the list        // and lit position does not change, but new element will be before lit        // lit's next is still 1, but lit's previous becomes 100        lit.add(100);
        System.out.println("--- lit.add(100) ----");
        System.out.println("lit.previousIndex(): " + lit.previousIndex());
        System.out.println("lit.nextIndex(): " + lit.nextIndex());


//        while(lit.hasPrevious()) {//            Integer i = lit.next();//            System.out.println("i: "+ i);//            lit.remove();//        }
        lit.add(100);

        System.out.println("lit.previousIndex(): " + lit.previousIndex());

        System.out.println("lit.nextIndex(): " + lit.nextIndex());

        Integer val = lit.next();
        lit.set(0);

        Iterator<Integer> it2 = list.iterator();

        while(it2.hasNext()) {
            Integer i = it2.next();
            System.out.println("i: "+ i);
            //it.remove();        }

    }

    // <T> must be declared before void to indicate compiler this is a generic method    static <T> void printCollection(Collection<T> c) {
        StringBuilder sb = new StringBuilder();
        for(Iterator it = c.iterator(); it.hasNext(); ){
            sb.append(it.next() + " -> ");
        }
        System.out.println(sb.toString());

        // or        // for(T t : c ){        //    sb.append(c);        // }        // System.out.println(sb.toString());    }
}

java special for collection size, array size, and string size

Size: For Collections (eg: Map, List, etc ): usually it use collection.size(), eg         Map<Character, Integer> map ...