apache-common-collections

New collection

Bag

Bag defines a set of: collecting a number of object appears.
For example Bag: {a, a, b , c}
call bag.getCount(a)returns 2, which means that there are two a.
Call bag.uniqueSet()returns a set, the value of {a, b, c}.

This set can be used to count, and if the set can not be achieved with a map can barely count as a value to achieve, but apparently when the add operation is not elegant, it is necessary:

map.put(key,map.get(key)+1);

And also need to worry about the memory map is not an integer.
Rabbit forest calculation Bag:

HashBag bag = new HashBag();
bag.add("rabbit",1);
bag.add("fox",1);
bag.add("rabbit",2);

//rabbit count
System.out.print(bag.getCount("rabbit"));
//how many animals
System.out.print(bag.uniqueSet().size());

In addition to HashBag, there SynchronizedBag, TreeBag, you can learn more about the source or by using javadoc.

Bhidinap

BidiMap defines a map, can be obtained not only by the value key, may also be obtained through the key value. Bidi mean bidirectional, two-way use of the map.
In addition to the operation of a conventional map, a special operation is as follows:

BidiMap bidi = new DualHashBidiMap();
bidi.put("k1","v1");
bidi.put("k2","v2");

bidi.get("k2"); // return v2
bidi.getKey("v2"); // return k2

bidi.inverseBidiMap(); //反转bidi,原先的value作为key

As the price, BidiMap requirements must k and v is one to one, after the code can not be done bidi.put("k2","v1");, because the response operation can not be achieved.
In reality, such as student number and ID number corresponding to do is such a relationship, as the case may be used.

In addition to DualHashBidiMap, there TreeBidiMap, etc., you can learn more about the source or by using javadoc.

The new concept

Predicate prophecy

This class is mainly combined CollectionUtils.find,CollectionUtils.filterto use.
His role is similar to "assert", which is only one way:

public boolean evaluate(Object object);

This method is used to determine whether an object meet certain criteria, you can> 50 to find that the list of objects older than 50 elements, or find the id of 12306 by letting age, such as

Predicate predicate = new Predicate{
  @override
  public boolean evaluate(Object object){
    return PropertyUtils.getSimpleProperty(object,"age") >50 ;
  }
}
Predicate predicate2 = new Predicate{
  @override
  public boolean evaluate(Object object){
    return PropertyUtils.getSimpleProperty(object,"id") == 12306 ;
  }
}
//删除不满足条件的结果
CollectionUtils.filter(list,predicate);
//返回第一个满足的元素
Object obj = CollectionUtils.find(list,predicate2);

Meanwhile, the Predicate predicate can be connected, by means of:

  • AndPredicate
  • OrPredicate
  • AnyPredicate
  • NotPredicate
    we can create with id 12306 prophecy and older than 50
new AndPredicate(predicate1,predicate2);

The degree of code reuse is greatly improved, this class is the essence of apache-common package at.

Closure closures and codes Transformer

These two interfaces introduced the main purpose is to expand the idea, because with the introduction of jdk8, the authors believe that these two interfaces on the questionable role of the. But when they introduced this idea is certainly worth considering.
We come to understand a piece of code from the two classes.

//传统代码
..do something
for(obj in list){
  obj.sayHello();
}
..do otherthing

//使用closure
Closure closure = ClosureUtils.invokerClosure("sayHello");

..do something
CollectionUtils.forAllDo(list,closure);
..do otherthing

Yes, this is functional programming ideas jdk8 vigorously introduced. Under the influence of other dynamic languages (javascript, scala, python, etc.) height, developers are aware of the benefits of functional programming.
The greatest benefit is to reduce the level block of code, the for, if, swith, while the nested structure of the code and so on in order to change the order type of structure, so that greatly enhance code readability. In fact the author's own feelings, too, and difficult to understand the degree proportional to the depth of nested code with a long code.

Imagine:

for(condition){
  if(cond2){
    if(cond4){
      ..do trunk logic
    }else{
      ..do branch logic
    }
  }else{
    if(cond3){
      ..do fast fail logic
    }
    ..do error fixing logic
  }
}

Talking about this, you can officially introduce Closure and Transformer. Their meanings are a packaging block code structure, the former is void function, which is a function that returns a value, can be interpreted as an object transform.
jdk8 formally introduced lambda functions, our solutions can be:

//forEach函数实现内部迭代
list.forEach(o->{System.out.println(o);});

Want to say here is that a variety of techniques, ideas unchanged

A set of new faces and old

In this section I will fly and listed a series of classes, specific use can explore on their own.

  • GrowthList
    List container in order to avoid the use of the most IndexOutOfBoundsException. Will be quiet for processing cross-border index: more than a set length and add operation is automatically increased to accommodate the list.

  • LazyList
    to implement lazy loading by passing a factory object. Growth also has features, such as the time get a non-existent index, it will automatically create an object and return.

[1,2,3].get(5)会导致:[1,2,3,null,factory.create()]
  • SetUniqueList
    interior is a set of list, we often need to use no repeat of the list, it creates a new ArrayList, and the last call
    new ArrayList(new HashSet(list))to come and go heavy. And this class will automatically help you do this well.

  • SynchronizedList
    a thread-safe list

  • LazyMap
    similar LazyList

  • LRUMap
    a limited number of Map, and to determine which elements are discarded, suitable for applications according to the simple cache LRU algorithm.

  • MultiKeyMap
    plurality Map key, such operation class, student number when:

map.put("class1",1001,john);

But after reading the source code is found by combining multiple key hashcode to do this, and then we put directly to use ordinary map ( "class1" + 1001, john) a similar effect. It can only be understood as to enhance the readability of the code.

  • MultiValueMap
    this class can easily corresponds to a case where a plurality of key value do adaptation.
    If, however, about Google's Guava package, there are actually a better use of class: Multimaphere is not to introduce too much.

  • CompositeCollection
    including CompositeSet, CompositeMap, while maintaining other container for each container provides the function of mixing.

To CompositeSet for example,
compositeSet.add(set1,set2);
the formation of a Grade II set, and this set1.addAll(set2)is not the same, we can use when there is set1, set2 and compositeSet at the same time.
Direct impact on the secondary set of sub-containers to modification action.
As compositeSet.remove(obj);
if set1 and set2 contains the obj, it will also be deleted obj.

Useful Tools

This is part of a package of the most valuable collections, I am prepared to introduce ListUtilsand CollectionUtils.

ListUtils list of tools

  • ListUtils.intersection (list1, list2)
    intersected
  • ListUtils.subtract (list1, list2)
    returns the difference list1 and list2. The difference here and list1.removeAll (list2) that:
    • The former does not change any collection
    • If there are two list1 a, list2 there is a a: removeAll list1 will all have a wipe, and subtract the result list1 still remaining a a
  • ListUtils.union (list1, list2)
    take the union
  • ListUtils.removeAll (list1, list2)
    do removeAll without changing the list of

CollectionUtils common set of tools

  • CollectionUtils.union (c1, c2), CollectionUtils.intersection (c1, c2)
    are not explained
  • CollectionUtils.disjunction (c1, c2)
    returns two disjoint parts and set, I did not expect a real scene. .
  • CollectionUtils.containsAny (c1, c2)
    as long as any element comprising a c1 c2 returns true

High-energy front :

  • CollectionUtils.find (c, predicate)
    important ways: With Predicate achieve godlike effect, cut in half from the for loop. It returns the first element found

  • CollectionUtils.filter (c, predicate)
    important ways: as above, directly change the container c.

  • CollectionUtils.transform (c, transformer)
    important ways: or artifact, but is equivalent to the foreach method jdk8 effect. If jdk <8, this method can be used in place of

  • CollectionUtils.countMatches (c, predicate)
    according to predicate returns the number of elements to meet the predicted return value int.

  • CollectionUtils.select (c, predicate)
    to identify the elements meet according to predicate, the composition of the new collection and return

  • CollectionUtils.select (c, predicate, outputCollection)
    find an element satisfying according predicate, was added to the outputCollection.

  • CollectionUtils.isEmpty (c)
    simple and practical, is null or empty set

Guess you like

Origin blog.csdn.net/ryuenkyo/article/details/92827924