@ -48,7 +48,10 @@ import java.util.Collections;
import java.util.Iterator ;
import java.util.List ;
import java.util.NoSuchElementException ;
import java.util.function.BinaryOperator ;
import java.util.stream.Collector ;
import org.eclipse.jgit.annotations.Nullable ;
import org.eclipse.jgit.lib.Ref ;
import org.eclipse.jgit.lib.RefComparator ;
@ -332,6 +335,32 @@ public class RefList<T extends Ref> implements Iterable<Ref> {
return r . toString ( ) ;
}
/ * *
* Create a { @link Collector } for { @link Ref } .
*
* @param mergeFunction
* if specified the result will be sorted and deduped .
* @return { @link Collector } for { @link Ref }
* @since 5 . 4
* /
public static < T extends Ref > Collector < T , ? , RefList < T > > toRefList (
@Nullable BinaryOperator < T > mergeFunction ) {
return Collector . of (
( ) - > new Builder < > ( ) ,
Builder < T > : : add , ( b1 , b2 ) - > {
Builder < T > b = new Builder < > ( ) ;
b . addAll ( b1 ) ;
b . addAll ( b2 ) ;
return b ;
} , ( b ) - > {
if ( mergeFunction ! = null ) {
b . sort ( ) ;
b . dedupe ( mergeFunction ) ;
}
return b . toRefList ( ) ;
} ) ;
}
/ * *
* Builder to facilitate fast construction of an immutable RefList .
*
@ -404,6 +433,16 @@ public class RefList<T extends Ref> implements Iterable<Ref> {
list [ size + + ] = ref ;
}
/ * *
* Add all items from another builder .
*
* @param other
* @since 5 . 4
* /
public void addAll ( Builder other ) {
addAll ( other . list , 0 , other . size ) ;
}
/ * *
* Add all items from a source array .
* < p >
@ -444,6 +483,31 @@ public class RefList<T extends Ref> implements Iterable<Ref> {
Arrays . sort ( list , 0 , size , RefComparator . INSTANCE ) ;
}
/ * *
* Dedupe the refs in place . Must be called after { @link # sort } .
*
* @param mergeFunction
* /
@SuppressWarnings ( "unchecked" )
void dedupe ( BinaryOperator < T > mergeFunction ) {
if ( size = = 0 ) {
return ;
}
int lastElement = 0 ;
for ( int i = 1 ; i < size ; i + + ) {
if ( RefComparator . INSTANCE . compare ( list [ lastElement ] ,
list [ i ] ) = = 0 ) {
list [ lastElement ] = mergeFunction
. apply ( ( T ) list [ lastElement ] , ( T ) list [ i ] ) ;
} else {
list [ lastElement + 1 ] = list [ i ] ;
lastElement + + ;
}
}
size = lastElement + 1 ;
Arrays . fill ( list , size , list . length , null ) ;
}
/** @return an unmodifiable list using this collection's backing array. */
public RefList < T > toRefList ( ) {
return new RefList < > ( list , size ) ;