Java – use limit connection string
Using only the standard Java library, what is a simple mechanism for concatenating strings to restrictions and appending ellipsis when restrictions result in shorter strings?
Efficiency is desirable Connect all strings and use string Substring () may consume too much memory and time The mechanism that can be used in Java 8 stream pipeline is desirable, so it may never even create strings that exceed the limit
For my purposes, I am satisfied with the limitations expressed in the following two ways:
>Maximum number of strings to add > maximum number of characters in the result, including any delimiters
For example, this is a way to enforce the maximum number of connection strings in Java 8 using the standard library Is there a simpler way?
final int LIMIT = 8; Set<String> mySet = ...; String s = mySet.stream().limit( LIMIT ).collect( Collectors.joining(",")); if ( LIMIT < mySet.size()) { s += ",..."; }
Solution
You can write a custom collector for this This is based on another I write for a similar case:
private static Collector<String,List<String>,String> limitingJoin(String delimiter,int limit,String ellipsis) { return Collector.of( ArrayList::new,(l,e) -> { if (l.size() < limit) l.add(e); else if (l.size() == limit) l.add(ellipsis); },(l1,l2) -> { l1.addAll(l2.subList(0,Math.min(l2.size(),Math.max(0,limit - l1.size())))); if (l1.size() == limit) l1.add(ellipsis); return l1; },l -> String.join(delimiter,l) ); }
In this code, we keep an ArrayList < string > all the popular string bands When an element is accepted, the size of the current list will be tested according to the limit: strictly less than it, add elements; Equals it, omitting the ellipsis The same is true for the combiner section, which is a bit tricky because we need to handle the size of the sub list correctly without exceeding the limit Finally, the terminator simply adds to the list using the given delimiter
This implementation applies to parallel streams It will retain the head element of stream in encounterorder Note that even if no elements are added after the limit is reached, it consumes all elements in the stream
Working example:
List<String> list = Arrays.asList("foo","bar","baz"); System.out.println(list.stream().collect(limitingJoin(",",2,"..."))); // prints "foo,bar,..."