What is the shortest way to initialize List of strings in java?

后端 未结 7 899
无人共我
无人共我 2020-12-04 17:39

I am searching for the shortest way (in code) to initialize list of strings and array of strings, i.e. list/array containing \"s1\", \"s2\", \"s3\" string elements.

7条回答
  •  失恋的感觉
    2020-12-04 17:57

    With Eclipse Collections, you can write the following:

    List list = Lists.mutable.with("s1", "s2", "s3");
    

    You can also be more specific about the types and whether they are Mutable or Immutable.

    MutableList mList = Lists.mutable.with("s1", "s2", "s3");
    ImmutableList iList = Lists.immutable.with("s1", "s2", "s3");
    

    You can also do the same with Sets, Bags and Maps:

    Set set = Sets.mutable.with("s1", "s2", "s3");
    MutableSet mSet = Sets.mutable.with("s1", "s2", "s3");
    ImmutableSet iSet = Sets.immutable.with("s1", "s2", "s3");
    
    Bag bag = Bags.mutable.with("s1", "s2", "s3");
    MutableBag mBag = Bags.mutable.with("s1", "s2", "s3");
    ImmutableBag iBag = Bags.immutable.with("s1", "s2", "s3");
    
    Map map = 
        Maps.mutable.with("s1", "s1", "s2", "s2", "s3", "s3");
    MutableMap mMap = 
        Maps.mutable.with("s1", "s1", "s2", "s2", "s3", "s3");
    ImmutableMap iMap = 
        Maps.immutable.with("s1", "s1", "s2", "s2", "s3", "s3");
    

    There are factories for SortedSets, SortedBags and SortedMaps as well.

    SortedSet sortedSet = SortedSets.mutable.with("s1", "s2", "s3");
    MutableSortedSet mSortedSet = SortedSets.mutable.with("s1", "s2", "s3");
    ImmutableSortedSet iSortedSet = SortedSets.immutable.with("s1", "s2", "s3");
    
    SortedBag sortedBag = SortedBags.mutable.with("s1", "s2", "s3");
    MutableSortedBag mSortedBag = SortedBags.mutable.with("s1", "s2", "s3");
    ImmutableSortedBag iSortedBag = SortedBags.immutable.with("s1", "s2", "s3");
    
    SortedMap sortedMap =
            SortedMaps.mutable.with("s1", "s1", "s2", "s2", "s3","s3");
    MutableSortedMap mSortedMap =
            SortedMaps.mutable.with("s1", "s1", "s2", "s2", "s3","s3");
    ImmutableSortedMap iSortedMap =
            SortedMaps.immutable.with("s1", "s1", "s2", "s2", "s3","s3");
    

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题