Search Java Code Snippets


  Help us in improving the repository. Add new snippets through 'Submit Code Snippet ' link.





#Java - Code Snippets for '#Java.util' - 85 code snippet(s) found

 Sample 1. Get all elements greater than 2, sort them and then push them to a new set, using Lambda Expression

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);

// Set the predicate or the condition for filtering the elements.

Predicate<Integer> moreThan2Pred = (p) -> (p > 1);

// Use Filter to refine the element set, sort to Sort and Collectors.toSet to get a set out of Stream.

intSet = intSet.stream().filter(moreThan2Pred).sorted().collect(Collectors.toSet());

System.out.println(intSet); // Prints [2, 3, 4]

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   predicate   filter   sort  java.util.hashset  java.util.stream.Collectors


 Sample 2. Combine two Summaries and Generate a new Summary using Lambda Expression

// Populate a List using Set elements.

// Declare and Initialize the Collection

Set<Integer> intSet = new HashSet<Integer>();
Set<Integer> intSet2 = new HashSet<Integer>();

// Add Elements

intSet.add(1);
intSet.add(2);
intSet.add(3);
intSet.add(4);
intSet2.add(1);
intSet2.add(2);
intSet2.add(3);
intSet2.add(4);

// Use the stream and collectors to Summarize all Integer elements

IntSummaryStatistics summary = intSet.stream().collect(Collectors.summarizingInt(p->((Integer)p)));

summary.combine(intSet2.stream().collect(Collectors.summarizingInt(p->((Integer)p))));

System.out.println(summary); // Prints IntSummaryStatistics{count=8, sum=20, min=1, average=2.500000, max=4}

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.summarizingInt   summary.combine  java.util.hashset  java.util.stream.Collectors  java.util.IntSummaryStatistics


 Sample 3. Generate Random Number till 100

Random rand = new Random();
int randomNumber = rand.nextInt(100);

   Like      Feedback     Random Number Generation  Random


 Sample 4. Blogger API for creating Posts ( Change xxxxxx to your blog specific info )

package Reader;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;

public class BlogPostCreater {

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

OkHttpClient client = new OkHttpClient();

String post(String title, String content,String label,String authorization_key) throws IOException {

content = content.replace(""",""");


String url = "https://www.googleapis.com/blogger/v3/blogs/xxxxxxxxxx/posts?clientId=xxxxxxxx&clientSecret=xxxxxxxx";

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);

// add header
post.setHeader("Authorization", authorization_key);
post.setHeader("Content-type","application/json");

post.setEntity(new StringEntity(buildJson(title,content,label)));

HttpResponse response = client.execute(post);

System.out.println(response);

return "true";
}



String buildJson(String title, String content,String label) {

System.out.println(label);
return "{"status": "LIVE", "content": ""+content+"", "kind": "blogger#post"" +
", "title": ""+title+"", "url": "xxxxxx", " +
""readerComments": "DONT_ALLOW_HIDE_EXISTING", "author": {" +
""url": "https://www.blogger.com/profile/04326686331881561093", " +
""image": {" +
""url": "//lh4.googleusercontent.com/-64Ucx9lX9Q4/AAAAAAAAAAI/AAAAAAAAAx0/-rUjBgS3djE/s35-c/photo.jpg"" +
"}, " +
""displayName": "Vivek Vermani", " +
""id": "g108356395081185480077"" +
"}, "updated": "2015-09-28T09:46:12+05:30", "replies": {"totalItems": "0", " +
""selfLink": "https://www.googleapis.com/blogger/v3/blogs/xxxxxxxxxx/posts/2495464003469367152/comments"" +
"}, "blog": {"id": "4275342475651800664"}, " +
""etag": "'GtyIIQmNmmUjEA0nwhSqMElCJ1g/dGltZXN0YW1wOiAxNDQzNDEzNzcyMDc1Cm9mZnNldDogMTk4MDAwMDAK'", " +
""published": "2015-09-28T09:46:00+05:30", " +
""id": "2495464003469367152", " +
""selfLink": "https://www.googleapis.com/blogger/v3/blogs/xxxxxx/posts/2495464003469367152"}";
}

public String post(String url, Map<String,String> formParameters) throws ClientProtocolException, IOException {
HttpPost request = new HttpPost(url);

List <NameValuePair> nvps = new ArrayList <NameValuePair>();

for (String key : formParameters.keySet()) {
nvps.add(new BasicNameValuePair(key, formParameters.get(key)));
}

request.setEntity(new UrlEncodedFormEntity(nvps));

return execute(request);
}

// makes request and checks response code for 200
private String execute(HttpRequestBase request) throws ClientProtocolException, IOException {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);

HttpEntity entity = response.getEntity();
String body = EntityUtils.toString(entity);

if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Expected 200 but got " + response.getStatusLine().getStatusCode() + ", with body " + body);
}

return body;
}


}

   Like      Feedback     blogger api   blogger api for post creation  java.lang.RuntimeException


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 5. Write a Program for Graph Breadth First Traversal using Apache Commons MultiMap

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Graph {
   private static Multimap<Integer,Integer> adjacentDirectedNodesMap = ArrayListMultimap.create();
   private static Set<Integer> alreadyVisited = new HashSet();
   
   static{
      adjacentDirectedNodesMap.put(1, 2);
      adjacentDirectedNodesMap.put(1, 3);
      adjacentDirectedNodesMap.put(1, 5);
      adjacentDirectedNodesMap.put(2, 4);
      adjacentDirectedNodesMap.put(4, 5);
   }
   
   public static void main(String[] args){
      ArrayList visited = new ArrayList();
      
      Integer startNode = 1;
      
      displayAdjacentNodes(startNode);
      
   }
   
   private static void displayAdjacentNodes(Integer integer){
      System.out.println(integer);
      for(Map.Entry<Integer, Collection<Integer>> adjacentNodes: adjacentDirectedNodesMap.asMap().entrySet()){
         for(Integer integer1:adjacentNodes.getValue()){
            if(alreadyVisited.contains(integer1)){
               continue;
            }
            alreadyVisited.add(integer1);
            System.out.println(integer1);
         }
      }
   }
   
}

   Like      Feedback     graph traversal  breadth first traversal


 Sample 6. Code to find email ids in a string using Pattern.

String text="vivek boy goy vivek@tech.com viv@ek.com sdjs@adjk";
Pattern regex = Pattern.compile("[@]");
Matcher regexMatcher = regex.matcher(text);
int i =0;
int width = 0;
while (regexMatcher.find()) {
if((regexMatcher.start()-10 > 0) && (regexMatcher.end()+10 < text.length())){
width=10;
String[] substr=text.substring(regexMatcher.start()-width,regexMatcher.end()+width).split(" ");
for(int j=0;j<substr.length;j++){
if(substr[j].contains("@") && (substr[j].contains(".com") || substr[j].contains(".net"))){
System.out.println(substr[j]);
}
}
} else {
width=0;
}
}

   Like      Feedback     regex  pattern  string  regexMatcher.find  java.util.regex.Matcher  java.util.regex.Pattern


 Sample 7. Enum with a method to get the constant having specific member element.

public enum JavaFramework {
SPRING("Spring","Web"),
STRUTS("Struts","Web"),
JSF("JSF","View"),
CRUNCH("Apache Crunch","BigData");


public String name;
public String type;

JavaFramework(String name, String type){
this.name = name;
this.type = type;
}

static public List<JavaFramework> getByType(String type) {
List<JavaFramework> frameworks = new ArrayList();
for(JavaFramework framework: JavaFramework.values()){
if(framework.type.equalsIgnoreCase(type)){
frameworks.add(framework);
}
}

return frameworks;
}
}

   Like      Feedback     enum  java.util.list


 Sample 8. Scheduling task using java.util.timer

static {
timer.schedule(new ScheduledTask(), 60000, 60000);
}

private static class Schedule extends TimerTask {
@Override public void run() {
//doSomething();
}
}

   Like      Feedback     java.util.timer  java.util.TimerTask  scheduling task  java.lang  Override


 Sample 9. Convert Time in milliseconds to Days

TimeUnit.DAYS.convert(timeinMs, TimeUnit.MILLISECONDS)

   Like      Feedback     convert time in ms to days  TimeUnit  java.util.concurrent.TimeUnit


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 10. Usage of LinkedHashMap


Map<String,String> linkedhashmap = new LinkedHashMap();
linkedhashmap.put("United States", "Washington");
linkedhashmap.put("Canada", "Ottawa");
linkedhashmap.put("Canada", "Ottawa");
linkedhashmap.put("South Africa", "Pretoria");
linkedhashmap.put("South Africa", "Cape Town");
linkedhashmap.put("South Africa", "Bloemfontein");

System.out.println(linkedhashmap); // Duplicates not allowed as it's a Map, Insertion Order as its linked Map

   Like      Feedback     LinkedHashMap  Map  HashMap  java.util  collections framework


 Sample 11. Code Sample / Example / Snippet of java.util.zip.DeflaterOutputStream

    private byte[] deflate(byte[] b) throws IOException {

ByteArrayOutputStream baos = new ByteArrayOutputStream();

DeflaterOutputStream dos = new DeflaterOutputStream(baos);

dos.write(b);

dos.close();

return baos.toByteArray();

}


   Like      Feedback      java.util.zip.DeflaterOutputStream


 Sample 12. Code Sample / Example / Snippet of java.util.zip.GZIPInputStream

  private static CSVReader openCsv(File file) throws IOException {

final Reader fileReader;

if (file.getName().endsWith(".gz")) {

final GZIPInputStream inputStream =

new GZIPInputStream(new FileInputStream(file));

fileReader = new InputStreamReader(inputStream);

} else {

fileReader = new FileReader(file);

}

return new CSVReader(fileReader);

}


   Like      Feedback      java.util.zip.GZIPInputStream


 Sample 13. Code Sample / Example / Snippet of java.util.Properties

    public Connection createConnection() throws SQLException {

final Properties info = new Properties();

for (Map.Entry<String, String> entry : map.entrySet()) {

info.setProperty(entry.getKey(), entry.getValue());

}

Connection connection =

DriverManager.getConnection("jdbc:calcite:", info);

for (ConnectionPostProcessor postProcessor : postProcessors) {

connection = postProcessor.apply(connection);

}

return connection;

}


   Like      Feedback      java.util.Properties


 Sample 14. Code Sample / Example / Snippet of java.util.jar.JarOutputStream

    private File createBundle(String symbolicName, String version) throws IOException {

File tmpFile = File.createTempFile("tmpbundle-", "jar");

tmpFile.deleteOnExit();

Manifest manifest = new Manifest();

manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

if (symbolicName != null) {

manifest.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, symbolicName);

}

if (version != null) {

manifest.getMainAttributes().putValue(Constants.BUNDLE_VERSION, version);

}

JarOutputStream target = new JarOutputStream(new FileOutputStream(tmpFile), manifest);

target.close();

return tmpFile;

}


   Like      Feedback      java.util.jar.JarOutputStream


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 15. Write a Program for Graph Depth First Traversal using Apache Commons MultiMap

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class Graph {
   private static Multimap<Integer,Integer> adjacentDirectedNodesMap = ArrayListMultimap.create();
   private static Set<Integer> alreadyVisited = new HashSet();
   
   static{
      adjacentDirectedNodesMap.put(1, 2);
      adjacentDirectedNodesMap.put(1, 3);
      adjacentDirectedNodesMap.put(1, 5);
      adjacentDirectedNodesMap.put(2, 4);
      adjacentDirectedNodesMap.put(4, 5);
   }
   
   public static void main(String[] args){
      ArrayList visited = new ArrayList();
      
      Integer startNode = 1;
      
      displayAdjacentNodes(startNode);
      
   }
   
   private static void displayAdjacentNodes(Integer integer){
      if(alreadyVisited.contains(integer)){
         return;
      }
      alreadyVisited.add(integer);
      System.out.println(integer);
      for(Integer adjacentNodes: adjacentDirectedNodesMap.get(integer)){
         displayAdjacentNodes(adjacentNodes);
      }
   }
   
}

   Like      Feedback     graph traversal  depth first algorithm


 Sample 16. Java Code to get all images url from html code.

regex = Pattern.compile("[http]");
regexMatcher = regex.matcher(htmlParseData.getHtml());
List tr=htmlParseData.getOutgoingUrls();
imgUrlCounter=0;
for(i=0;i<tr.size();i++){
if(tr.get(i).toString().contains(".jpg") || tr.get(i).toString().contains(".jpeg") || tr.get(i).toString().contains(".gif") || tr.get(i).toString().contains(".bmp")){
url = new URL(tr.get(i).toString());
Image image = new ImageIcon(url).getImage();
}
}

   Like      Feedback     regex  pattern  regex.matcher  html  java.util.regex.pattern  regular expressions


 Sample 17. Usage of HashMap

Map<Integer,String> indexedInfo = new HashMap();
indexedInfo.put(1,"Spain");
indexedInfo.put(2,"Denmark");
indexedInfo.put(3,"China");

   Like      Feedback     hashmap  map  collections  java.util.hashmap


 Sample 18. Sort a List using Collections.sort and comparator

Collections.sort(listClassInfo,new Comparator<ClassInfoBean>(){
public int compare(ClassInfoBean s1,ClassInfoBean s2){
if(s1.name.compareTo(s2.name) < 0){
return -1;
} else {
return 1;
}

}});

   Like      Feedback     sorting   sort   Collections.sort   sort a list   comparator   compare method  java.util.Collections


 Sample 19. ArrayList of Optional Integers

List<Optional<Integer>> intList = new ArrayList<Optional<Integer>>();

// Add Elements

intList.add(Optional.empty());
intList.add(Optional.of(2));
intList.add(Optional.of(3));
intList.add(Optional.of(4));

   Like      Feedback     optional  java 8   list   arraylist   list of optional integers   arraylist of optional  java.util.Optional


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 20. Get current time using GregorianCalendar

Calendar calendar = new GregorianCalendar();
float currentTime = calendar.get( Calendar.HOUR_OF_DAY ) + ((float)calendar.get( Calendar.MINUTE )/100);

   Like      Feedback     GregorianCalendar  Calendar.HOUR_OF_DAY  Calendar.MINUTE  Calendar.java.util.Calendar


 Sample 21. LinkedList of optional Integers

List<Optional<Integer>> intList = new LinkedList<Optional<Integer>> ();

// Add Elements

intList.add(Optional.empty());
intList.add(Optional.of(2));
intList.add(Optional.of(3));
intList.add(Optional.of(4));

   Like      Feedback     


 Sample 22. Initialize java.util.date using java.util.Calendar

Date currentDate = Calendar.getInstance().getTime();

   Like      Feedback     calendar  java.util.calendar  java.util  date  java.util.date  Calendar.getTime


 Sample 23. Initialize list using google guava Lists

import java.util.List;
import com.google.common.collect.Lists;

class GoogleListsTest{
public static void main(String[] args){
List list = Lists.newArrayList();
}
}

   Like      Feedback     list  google guava  Lists  Lists.newArrayList  com.google.common.collect.Lists


 Sample 24. Write a Program for coin changer application. The program should set the cash box with available currency and then should render the exact change. If enough cash is not available , it should present the appropriate message.

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;


public class CoinChanger {

enum Currency {
DOLLAR(1),QUARTER(.25),DIME(.10),NICKEL(.05),PENNY(.01);

private double currencyValue;

Currency(double value){
currencyValue = value;
}

double getCurrencyValue(){
return this.currencyValue;
}
}

private static Map<Currency, Integer> cashBox;
private static Map<Currency, Integer> change;

static {
cashBox = new TreeMap<Currency, Integer>();
change = new TreeMap<Currency, Integer>();
initializeCashBox();
}



public static void main(String[] args) {
double amountToReturn = 18.79f; // Set the amount to be changed here

for(Entry<Currency, Integer> entry:cashBox.entrySet()){
Currency currency = (Currency)entry.getKey();
int coinCount = (int)(amountToReturn/(entry.getKey().getCurrencyValue()));
int availableCurrency = (int)(entry.getValue());

if(coinCount > availableCurrency){
coinCount = availableCurrency;
}

change.put(currency, coinCount);
if(coinCount > 0){
amountToReturn = amountToReturn - (coinCount * entry.getKey().getCurrencyValue());
}
}

System.out.println(change);

if(amountToReturn > .1){
System.out.println("Not enough cash");
}
}

private static void initializeCashBox(){
//set the cash box
cashBox.put(Currency.DOLLAR, 50);
cashBox.put(Currency.QUARTER, 0);
cashBox.put(Currency.DIME, 50);
cashBox.put(Currency.NICKEL, 50);
cashBox.put(Currency.PENNY, 50);

}
}

   Like      Feedback     coin changer application  coin changer app


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 25. Method to get Date after n days using Calendar

Date getDateAfterDays(int numberOfDays){
   Calendar futureDate = Calendar.getInstance();
   futureDate.setTime(new Date()); // Set Current Date
   futureDate.add(Calendar.DATE, numberOfDays); // Add n days to current Date

   return new Date(futureDate.getTimeInMillis());
}

   Like      Feedback     date   calendar   java.util  calendar.add  calendar.date  calendar.settime  calendar.gettimeinmillis


 Sample 26. Get Date and Time after few Hours

Date getDateTimeAfterNHours(int numberOfHours){
   Calendar futureTime = Calendar.getInstance();
   futureTime.setTime(new Date()); // Set Current Date
   futureTime.add(Calendar.HOUR, numberOfDays); // Add n hours to current Date and Time

   return new Date(futureTime.getTimeInMillis());
}

   Like      Feedback     date   calendar   java.util  calendar.add  calendar.hour  calendar.settime  calendar.gettimeinmillis


 Sample 27. Time Taken to call a method or service

Date date1 = new Date();

// Call Service or Method

Date date2 = new Date();
System.out.println(TimeUnit.SECONDS.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Seconds
System.out.println(TimeUnit.MINUTES.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Minutes
System.out.println(TimeUnit.HOURS.convert(date2.getTime()-date1.getTime(), TimeUnit.MILLISECONDS));// Time Taken in Hours

   Like      Feedback     Difference between 2 dates  Time to call a method  TimeUnit  Date.java.util.Date


 Sample 28. Spring AMQP ( messaging-rabbitmq ) - Register the listener and send a message

https://spring.io/guides/gs/messaging-rabbitmq/

   Like      Feedback     


 Sample 29. RabbitMQ message receiver

import java.util.concurrent.CountDownLatch;

public class Receiver {

   private CountDownLatch latch = new CountDownLatch(1);

   public void receiveMessage(String message) {
      latch.countDown();
   }

   public CountDownLatch getLatch() {
      return latch;
   }

}

   Like      Feedback     Spring AMQP  Rabbit MQ  RabbitMQ


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 30. Apache Kafka Producer

https://apache.googlesource.com/kafka/+/trunk/examples/src/main/java/kafka/examples/Producer.java

   Like      Feedback     


 Sample 31. Implementation of NamespaceContext

import java.util.Iterator;

import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;

// Map prefixes to Namespace URIs
public class APINameSpaceContext implements NamespaceContext
{
   static final String WEB_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/web";
   static final String API_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/element";
   static final String SPELL_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/spell";
   static final String RS_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/relatedsearch";
   static final String PB_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/phonebook";
   static final String MM_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/multimedia";
   static final String AD_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/ads";
   static final String IA_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/instantanswer";
   static final String NEWS_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/news";
   static final String ENCARTA_NAMESPACE = "http://schemas.microsoft.com/LiveSearch/2008/04/XML/encarta";

   public String getNamespaceURI(String prefix)
   {
      if (prefix == null) throw new NullPointerException("Null prefix");
      else if ("api".equals(prefix)) return API_NAMESPACE;
      else if ("web".equals(prefix)) return WEB_NAMESPACE;
      return XMLConstants.NULL_NS_URI;
   }
   
   // This method isn't necessary for XPath processing.
   public String getPrefix(String uri)
   {
      throw new UnsupportedOperationException();
   }
   
   public Iterator getPrefixes(String arg0)
   {
      throw new UnsupportedOperationException();
   }
}

   Like      Feedback     NamespaceContext


 Sample 32. Apache Hadoop Map Reduce Example

https://apache.googlesource.com/hadoop-common/+/trunk/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/Grep.java

   Like      Feedback     


 Sample 33. Apache Hadoop Multi File Word Count

https://apache.googlesource.com/hadoop-common/+/trunk/hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/MultiFileWordCount.java

   Like      Feedback     


 Sample 34. Usage of org.apache.abdera.model.Entry;

Entry entry = factory.newEntry();
entry.setId(FOMHelper.generateUuid());
entry.setUpdated(new java.util.Date());
entry.addAuthor("James");
entry.setTitle("Posting to Roller");
entry.setContentAsHtml("<p>This is an example post to Roller</p>");
AbderaClient abderaClient = new AbderaClient(abdera);
abderaClient.addCredentials(start, null, null, new UsernamePasswordCredentials("username", "password"));
Document<Service> service_doc = abderaClient.get(start).getDocument();
Service service = service_doc.getRoot();
Collection collection = service.getWorkspaces().get(0).getCollections().get(0);
String uri = collection.getHref().toString();
Response response = abderaClient.post(uri, entry);

   Like      Feedback     


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 35. Internal Implementation of ArrayList#removeIf

@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);

int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}

// shift surviving elements left over the spaces left by removed elements
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
for (int k=newSize; k < size; k++) {
elementData[k] = null; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}

return anyToRemove;
}

   Like      Feedback     Internal Implementation of ArrayList#removeIf  java.util.function.Predicate  java.util.Objects  java.util.Objects  java.util.ConcurrentModificationException.ConcurrentModificationException


 Sample 36. Internal Implementation of BufferedReader#lines

public Stream<String> lines() {
Iterator<String> iter = new Iterator<String>() {
String nextLine = null;

@Override
public boolean hasNext() {
if (nextLine != null) {
return true;
} else {
try {
nextLine = readLine();
return (nextLine != null);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
}

@Override
public String next() {
if (nextLine != null || hasNext()) {
String line = nextLine;
nextLine = null;
return line;
} else {
throw new NoSuchElementException();
}
}
};
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
iter, Spliterator.ORDERED | Spliterator.NONNULL), false);
}

   Like      Feedback     Internal Implementation of BufferedReader#lines


 Sample 37. Usage of org.joda.time.DateMidnight

DateMidnight currentDate = new DateMidnight();
DateMidnight dateafterAMonth = currentDate.plusMonths(1);
Date javaSedateAfterAMonth = dateafterAMonth.toDate();

   Like      Feedback     org.joda.time.DateMidnight  java.util.Date  Date  Add month to Date


 Sample 38. Check whether a reference of AbstractCollection holds a List,Queue or Set

public static void main(String[] args)  {
      
       AbstractCollection collection = new ArrayList();
      
       if(collection instanceof AbstractList){
          System.out.println("This is a list");
       }
      
       if(collection instanceof AbstractQueue){
          System.out.println("This is a Queue");
       }
      
       if(collection instanceof AbstractSet){
          System.out.println("This is a Set");
       }
      
}

   Like      Feedback     instaceOf  AbstractCollection


 Sample 39. Clear Map entries after expiration time using Apache commons PassiveExpiringMap

PassiveExpiringMap<String,String> cache = new PassiveExpiringMap<String,String>(1,TimeUnit.SECONDS); // Expiration time of 1 sec
cache.put("Key1", "Value1");
System.out.println(cache.containsKey("Key1")); // prints true
Thread.sleep(1000);
System.out.println(cache.containsKey("Key1")); // prints false

   Like      Feedback     Clear Map entries after expiration  PassiveExpiringMap  map  apache commons  TimeUnit.SECONDS  Thread.sleep


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 40. Make a map readonly using Apache Commons UnmodifiableMap

Map<String,String> map = new HashMap();
map.put("Key1", "Value1");

Map<String,String> unmodifiableMap = UnmodifiableMap.unmodifiableMap(map);
      
unmodifiableMap.put("Key2", "Value2"); // throws java.lang.UnsupportedOperationException

   Like      Feedback     readonly map  apache commons


 Sample 41. Usage of TreeMap

Map<String,String> treemap = new TreeMap();
treemap.put("United States", "Washington");
treemap.put("Canada", "Ottawa");
treemap.put("Canada", "Ottawa");
treemap.put("South Africa", "Pretoria");
treemap.put("South Africa", "Cape Town");
treemap.put("South Africa", "Bloemfontein");

System.out.println(treemap); // Duplicate Not allowed as it's a Map, Ordered by Keys as it's a TreeMap

   Like      Feedback     TreeMap  Map  java.util


 Sample 42. Usage of ConcurrentSkipListMap

Map<String,String> map = new ConcurrentSkipListMap();
map.put("United States", "Washington");
map.put("Canada", "Ottawa");
map.put("Canada", "Ottawa");
map.put("South Africa", "Pretoria");
map.put("South Africa", "Cape Town");
map.put("South Africa", "Bloemfontein");

System.out.println(map); // Prints {Canada=Ottawa, South Africa=Bloemfontein, United States=Washington}
      
// Duplicates not allowed as it's a Map, Sorted as par natural order of keys for faster and concurrent operations.

   Like      Feedback     map  ConcurrentSkipListMap  concurrent access map


 Sample 43. Usage of EnumMap

Map<Country,String> map = new HashMap();
map.put(Country.US, "Washington");
map.put(Country.CANADA, "Ottawa");
map.put(Country.CANADA, "Ottawa");
map.put(Country.SOUTH_AFRICA, "Pretoria");
map.put(Country.SOUTH_AFRICA, "Cape Town");
map.put(Country.SOUTH_AFRICA, "Bloemfontein");

Map<String,String> enumMap = new EnumMap(map); // Prints {CANADA=Ottawa, US=Washington, SOUTH_AFRICA=Bloemfontein}

System.out.println(enumMap); // Duplicates not allowed as it's a Map, Sorted as per order of Enum Declarations

   Like      Feedback     EnumMap  Collections framework  Map  Map with enum keys


 Sample 44. Get the Date object using the TimeZone

TimeZone zone = (TimeZone.getDefault().getRawOffset() == EET.getRawOffset() ? EST : EET);
Date expectedZone = createCalendar(zone, 20051231, 0).getTime();

   Like      Feedback     TimeZone  java.util.TimeZone  Date  Calendar


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 45. Usage of java.text.NumberFormat

NumberFormat formatter = null;
if (locale != null) {
formatter = NumberFormat.getNumberInstance(locale);
} else {
formatter = NumberFormat.getNumberInstance(Locale.getDefault());
}

   Like      Feedback     NumberFormat  Locale


 Sample 46. Usage of Java Collections Stack

Stack<INodeDirectory> directories = new Stack<INodeDirectory>();
for(directories.push((INodeDirectory)inode); !directories.isEmpty(); ) {
   INodeDirectory d = directories.pop();
}

   Like      Feedback     stack  collections  java.util


 Sample 47. Usage of java.util.concurrent.Future

long bytesLastMoved = bytesMoved.get();
Future<?>[] futures = new Future<?>[sources.size()];
int i=0;
for (Source source : sources) {
   futures[i++] = dispatcherExecutor.submit(source.new BlockMoveDispatcher());
}

for (Future<?> future : futures) {
   try {
      future.get();
   } catch (ExecutionException e) {
      LOG.warn("Dispatcher thread failed", e.getCause());
   }
}

   Like      Feedback     


 Sample 48. Code Sample / Example / Snippet of java.util.StringTokenizer

  public static List<String> getNamedOutputsList(JobConf conf) {

List<String> names = new ArrayList<String>();

StringTokenizer st = new StringTokenizer(conf.get(NAMED_OUTPUTS, ""), " ");

while (st.hasMoreTokens()) {

names.add(st.nextToken());

}

return names;

}


   Like      Feedback      java.util.StringTokenizer


 Sample 49. Code Sample / Example / Snippet of java.util.Calendar

    public static double year()

{

Calendar cal = Calendar.getInstance();

return cal.get(Calendar.YEAR);

}


   Like      Feedback      java.util.Calendar


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 50. Code Sample / Example / Snippet of java.util.EventListener

    private void readObject(ObjectInputStream s)

throws IOException, ClassNotFoundException {

listenerList = NULL_ARRAY;

s.defaultReadObject();

Object listenerTypeOrNull;



while (null != (listenerTypeOrNull = s.readObject())) {

ClassLoader cl = Thread.currentThread().getContextClassLoader();

EventListener l = (EventListener)s.readObject();

String name = (String) listenerTypeOrNull;

ReflectUtil.checkPackageAccess(name);

add((Class<EventListener>)Class.forName(name, true, cl), l);

}

}




   Like      Feedback      java.util.EventListener


 Sample 51. Concatenate two Streams

public static IntStream concat(IntStream a, IntStream b) {
Objects.requireNonNull(a);
Objects.requireNonNull(b);

Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt(
a.spliterator(), b.spliterator());
IntStream stream = StreamSupport.intStream(split, a.isParallel() || b.isParallel());
return stream.onClose(Streams.composedClose(a, b));
}

   Like      Feedback     Concatenate two Streams   java 8  java8


 Sample 52. Code Sample / Example / Snippet of java.util.Map

  public Schema create(SchemaPlus parentSchema, String name,

Map<String, Object> operand) {

Map map = (Map) operand;

String host = (String) map.get("host");

String database = (String) map.get("database");

return new MongoSchema(host, database);

}


   Like      Feedback      java.util.Map


 Sample 53. Code Sample / Example / Snippet of java.util.Random

  public Enumerable<Object[]> scan(DataContext root) {

final Random random = seed >= 0 ? new Random(seed) : new Random();

final Maze maze = new Maze(width, height);

final PrintWriter pw = new PrintWriter(System.out);

maze.layout(random, pw);

if (Maze.DEBUG) {

maze.print(pw, true);

}

return new AbstractEnumerable<Object[]>() {

public Enumerator<Object[]> enumerator() {

final Set<Integer> solutionSet;

if (solution) {

solutionSet = maze.solve(0, 0);

} else {

solutionSet = null;

}

return Linq4j.transform(maze.enumerator(solutionSet),

new Function1<String, Object[]>() {

public Object[] apply(String s) {

return new Object[] {s};

}

});

}

};

}


   Like      Feedback      java.util.Random


 Sample 54. Code Sample / Example / Snippet of java.util.TimeZone

  private static final FastDateFormat TIME_FORMAT_TIMESTAMP;



static {

TimeZone gmt = TimeZone.getTimeZone("GMT");

TIME_FORMAT_DATE = FastDateFormat.getInstance("yyyy-MM-dd", gmt);

TIME_FORMAT_TIME = FastDateFormat.getInstance("HH:mm:ss", gmt);

TIME_FORMAT_TIMESTAMP =

FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss", gmt);

}


   Like      Feedback      java.util.TimeZone


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 55. Code Sample / Example / Snippet of java.util.Calendar

  private SparkHandlerImpl() {

classServer = new HttpServer(CLASS_DIR);



classServer.start();

System.setProperty("spark.repl.class.uri", classServer.uri());



final Calendar calendar = Calendar.getInstance();

classId = new AtomicInteger(

calendar.get(Calendar.HOUR_OF_DAY) * 10000

+ calendar.get(Calendar.MINUTE) * 100

+ calendar.get(Calendar.SECOND));

}


   Like      Feedback      java.util.Calendar


 Sample 56. Code Sample / Example / Snippet of java.util.regex.Matcher

    private void defineVariables(String line) {

Matcher varDefn = matchesVarDefn.matcher(line);

if (varDefn.lookingAt()) {

String var = varDefn.group(1);

String val = varDefn.group(2);

vars.define(var, val);

} else {

String[] words = splitWords.split(line);

for (String var : words) {

String value = System.getenv(var);

vars.define(var, value);

}

}

}


   Like      Feedback      java.util.regex.Matcher


 Sample 57. Code Sample / Example / Snippet of java.util.StringTokenizer

    private List<String> tokenize(String s) {

List<String> result = new ArrayList<>();

StringTokenizer tokenizer = new StringTokenizer(s);

while (tokenizer.hasMoreTokens()) {

result.add(tokenizer.nextToken());

}

return result;

}


   Like      Feedback      java.util.StringTokenizer


 Sample 58. Code Sample / Example / Snippet of java.util.Collection

      public Void apply(ResultSet resultSet) {

++executeCount;

try {

final Collection result =

CalciteAssert.toStringList(resultSet,

ordered ? new ArrayList<String>() : new TreeSet<String>());

if (executeCount == 1) {

expected = result;

} else {

if (!expected.equals(result)) {

assertThat(newlineList(result), equalTo(newlineList(expected)));

fail("oops");

}

}

return null;

} catch (SQLException e) {

throw new RuntimeException(e);

}

}


   Like      Feedback      java.util.Collection


 Sample 59. Code Sample / Example / Snippet of java.util.BitSet

    public static BitSet INIT_BITSET(final int ... b) {

final BitSet bitset = new BitSet();

for (final int aB : b) {

bitset.set(aB);

}

return bitset;

}


   Like      Feedback      java.util.BitSet


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 60. Code Sample / Example / Snippet of java.util.List

    private static List convertArrayToList(Object array)

{

int len = Array.getLength(array);

List list = new ArrayList(len);

for (int i = 0; i < len; i++)

{

list.add(Array.get(array, i));

}

return list;

}


   Like      Feedback      java.util.List


 Sample 61. Code Sample / Example / Snippet of java.util.regex.Pattern

    private long getStoreId(File storeFile) {

Pattern p = Pattern.compile(m_name + "-(\d+)");

Matcher m = p.matcher(storeFile.getName());

if (m.find()) {

return Long.parseLong(m.group(1));

}

throw new RuntimeException("Invalid store file name: " + storeFile.getName());

}




   Like      Feedback      java.util.regex.Pattern


 Sample 62. Code Sample / Example / Snippet of java.util.concurrent.ScheduledExecutorService

    public void postEvent(final String topic, Map<String, String> payload) {

final Map<String, String> eventPayload = new HashMap<>(payload);

for (final EventListener listener : m_listeners) {

ScheduledExecutorService executor = getExecutorService();

if (executor.isShutdown()) {

logWarning("Cannot post event, executor is shut down!");

return;

}

executor.submit(new Runnable() {

@Override

public void run() {

try {

listener.handle(topic, eventPayload);

}

catch (Exception e) {

logWarning("Exception while posting event", e);

}

}

});

}

}


   Like      Feedback      java.util.concurrent.ScheduledExecutorService


 Sample 63. Code Sample / Example / Snippet of java.util.concurrent.locks.Lock

    public int getDeploymentVersionLimit() {

Lock lock = m_lock.readLock();

lock.lock();

try {

return m_deploymentVersionLimit;

}

finally {

lock.unlock();

}

}


   Like      Feedback      java.util.concurrent.locks.Lock


 Sample 64. Code Sample / Example / Snippet of java.util.Iterator

    public void validateRangeIterators() {

SortedRangeSet srs1 = new SortedRangeSet("1-10");

Iterator i1 = srs1.rangeIterator();

assert i1.hasNext() : "We should have one Range instance in our iterator.";

assert ((Range) i1.next()).toRepresentation().equals("1-10");

assert !i1.hasNext() : "There should be only one instance in our iterator.";

SortedRangeSet srs2 = new SortedRangeSet("1-5,8,10-15");

Iterator i2 = srs2.rangeIterator();

assert i2.hasNext() && i2.next() instanceof Range

&& i2.hasNext() && i2.next() instanceof Range

&& i2.hasNext() && i2.next() instanceof Range

&& !i2.hasNext() : "There should be exactly three Range instances in our iterator.";

SortedRangeSet srs3 = new SortedRangeSet("");

assert !srs3.iterator().hasNext() : "Iterator should be empty.";

}


   Like      Feedback      java.util.Iterator


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 65. Code Sample / Example / Snippet of java.util.Set

    public Set getExtendList() {

Set set = new HashSet();

for (Iterator i = requirements.iterator(); i.hasNext();) {

RequirementImpl impl = (RequirementImpl) i.next();

if (impl.isExtend())

set.add(impl);

}

return set;

}


   Like      Feedback      java.util.Set


 Sample 66. Code Sample / Example / Snippet of java.util.Random

    private File createRandomFileWithContent() throws IOException {

OutputStream fileOut = null;

File file = null;

try {

file = FileUtils.createTempFile(null);

fileOut = new FileOutputStream(file);

byte[] byteArray = new byte[12345];

Random randomContentCreator = new Random();

randomContentCreator.nextBytes(byteArray);

fileOut.write(byteArray);



return file;

}

finally {

try {

if (fileOut != null) {

fileOut.close();

}

}

catch (IOException e) {

throw e;

}

}

}


   Like      Feedback      java.util.Random


 Sample 67. Code Sample / Example / Snippet of java.util.StringTokenizer

	public LowestID(String representation) {

try {

StringTokenizer st = new StringTokenizer(representation, ",");

m_targetID = Codec.decode(st.nextToken());

m_storeID = Long.parseLong(st.nextToken());

m_lowestID = Long.parseLong(st.nextToken());

}

catch (NoSuchElementException e) {

throw new IllegalArgumentException("Could not create lowest ID object from: " + representation);

}

}


   Like      Feedback      java.util.StringTokenizer


 Sample 68. Code Sample / Example / Snippet of java.util.concurrent.CountDownLatch

    public void testTooLongTask() throws Exception {

final CountDownLatch latch = new CountDownLatch(5);



Executer executer = new Executer(new Runnable() {

public void run() {

try {

Thread.sleep(20);

latch.countDown();

}

catch (InterruptedException e) {

e.printStackTrace();

}

}

});

executer.start(10);

assert latch.await(1, TimeUnit.SECONDS);

}


   Like      Feedback      java.util.concurrent.CountDownLatch


 Sample 69. Code Sample / Example / Snippet of java.util.Calendar

    private static Calendar getToday() {

Calendar cal = Calendar.getInstance();

cal.set(Calendar.HOUR_OF_DAY, 12);

cal.set(Calendar.MINUTE, 0);

cal.set(Calendar.SECOND, 0);

cal.set(Calendar.MILLISECOND, 0);

return cal;

}


   Like      Feedback      java.util.Calendar


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 70. Code Sample / Example / Snippet of java.util.concurrent.Semaphore

    private void removeRepository(String instanceName) throws IOException, InterruptedException, InvalidSyntaxException {

Configuration[] configs = listConfigurations("(factory.instance.pid=" + instanceName + ")");

if ((configs != null) && (configs.length > 0)) {

final Semaphore sem = new Semaphore(0);

ServiceTracker<Object, Object> tracker = new ServiceTracker<Object, Object>(m_bundleContext, m_bundleContext.createFilter("(factory.instance.pid=" + instanceName + ")"), null) {

@Override

public void removedService(ServiceReference<Object> reference, Object service) {

super.removedService(reference, service);

sem.release();

}

};

tracker.open();



try {

configs[0].delete();



if (!sem.tryAcquire(1, TimeUnit.SECONDS)) {

throw new IOException("Instance did not get removed in time.");

}

}

finally {

tracker.close();

}

}

}


   Like      Feedback      java.util.concurrent.Semaphore


 Sample 71. Code Sample / Example / Snippet of java.util.jar.Manifest

    public InputStream getDeploymentPackage(String id, String version) throws OverloadedException, IOException {

List<ArtifactData> data = m_provider.getBundleData(id, version);

Manifest manifest = new Manifest();

Attributes main = manifest.getMainAttributes();



main.putValue("Manifest-Version", "1.0");

main.putValue("DeploymentPackage-SymbolicName", id);

main.putValue("DeploymentPackage-Version", version);



for (ArtifactData bd : data) {

manifest.getEntries().put(bd.getFilename(), bd.getManifestAttributes(false));

}



return DeploymentPackageStream.createStreamForThread(m_connectionFactory, manifest, data.iterator(), false);

}


   Like      Feedback      java.util.jar.Manifest


 Sample 72. Code Sample / Example / Snippet of java.util.jar.Attributes

    public InputStream getDeploymentPackage(String id, String version) throws OverloadedException, IOException {

List<ArtifactData> data = m_provider.getBundleData(id, version);

Manifest manifest = new Manifest();

Attributes main = manifest.getMainAttributes();



main.putValue("Manifest-Version", "1.0");

main.putValue("DeploymentPackage-SymbolicName", id);

main.putValue("DeploymentPackage-Version", version);



for (ArtifactData bd : data) {

manifest.getEntries().put(bd.getFilename(), bd.getManifestAttributes(false));

}



return DeploymentPackageStream.createStreamForThread(m_connectionFactory, manifest, data.iterator(), false);

}


   Like      Feedback      java.util.jar.Attributes


 Sample 73. Code Sample / Example / Snippet of java.util.Properties

    public void init(BundleContext context, DependencyManager manager) throws Exception {

manager.add(createComponent()

.setInterface(Servlet.class.getName(), null)

.setImplementation(DeploymentServlet.class)

.add(createConfigurationDependency().setPropagate(true).setPid(DEPLOYMENT_PID))

.add(createServiceDependency().setService(StreamGenerator.class).setRequired(true))

.add(createServiceDependency().setService(DeploymentProvider.class).setRequired(true))

.add(createServiceDependency().setService(DeploymentProcessor.class).setRequired(false).setCallbacks("addProcessor", "removeProcessor"))

.add(createServiceDependency().setService(LogService.class).setRequired(false))

);

manager.add(createComponent()

.setInterface(Servlet.class.getName(), null)

.setImplementation(AgentDeploymentServlet.class)

.add(createConfigurationDependency().setPropagate(true).setPid(AGENT_PID))

.add(createServiceDependency().setService(ConnectionFactory.class).setRequired(true))

.add(createServiceDependency().setService(LogService.class).setRequired(false))

);



Properties props = new Properties();

props.put("pattern", "/*");

manager.add(createComponent()

.setInterface(Filter.class.getName(), null)

.setImplementation(OverloadedFilter.class)

);

}


   Like      Feedback      java.util.Properties


 Sample 74. Code Sample / Example / Snippet of java.util.concurrent.ExecutorService

    public void hundredStreamsConcurrently() throws Exception {

ExecutorService e = Executors.newFixedThreadPool(5);

for (int i = 0; i < 10; i++) {

e.execute(new Runnable() {

public void run() {

for (int i = 0; i < 10; i++) {

try {

isJarInputStreamReadable();

}

catch (Exception e) {

m_failure = e;

}

}

}

});

}

e.shutdown();

e.awaitTermination(10, TimeUnit.SECONDS);



assert m_failure == null : "Test failed: " + m_failure.getLocalizedMessage();

}




   Like      Feedback      java.util.concurrent.ExecutorService


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 75. Code Sample / Example / Snippet of java.util.Timer

    public void shutdown(long delay) {

Timer timer = new Timer();

timer.schedule(new TimerTask() {

@Override

public void run() {

try {

m_context.getBundle(0).stop();

}

catch (BundleException e) {

e.printStackTrace();

}

}

}, delay);

}


   Like      Feedback      java.util.Timer


 Sample 76. Code Sample / Example / Snippet of java.util.Vector

    private static final String DEFAULT_PROPERTIES_FILE = "QueueMonitor.properties";



String propertiesFile = DEFAULT_PROPERTIES_FILE;

String broker = "tcp://localhost:61616";

String connectID = "QueueMonitor";

String username = "QueueMonitor";

String password = "QueueMonitor";

String browseQueues = "Q1,Q2,Q3";

String textFontName = "Dialog";

String textFontStyle = "PLAIN";

String textFontSize = "12";

String title = "QueueMonitor";



JTextArea textArea = new JTextArea();

JScrollPane scrollPane = new JScrollPane(textArea);

JButton browseButton = new JButton("Browse Queues");



Vector theQueues = new Vector();


   Like      Feedback      java.util.Vector


 Sample 77. Write CSV values to a file using au.com.bytecode.opencsv.CSVWriter

String[] stringArray1 = new String[5];
String[] stringArray2 = new String[5];
String[] stringArray3 = new String[5];

List listOfStringArrays = new ArrayList();
listOfStringArrays.add(stringArray1);
listOfStringArrays.add(stringArray2);
listOfStringArrays.add(stringArray3);

File file = new File("BuggyBread.txt");
CSVWriter csvWriter = null;
try {
   csvWriter = new CSVWriter(new FileWriter(file),CSVWriter.DEFAULT_SEPARATOR);
} catch (Exception ex){
}
csvWriter.writeAll(listOfStringArrays);

   Like      Feedback     array of Strings  csv writer


 Sample 78. Usage of java.util.stream.Stream

List<Integer> list1 = Arrays.asList(1, 2);
List<Integer> list2 = Arrays.asList(4, 5);

Stream.of(list1, list1)
.flatMap(list -> list.stream())
.forEach(System.out::println);

   Like      Feedback     Stream.flatMap  System.out::println


 Sample 79. Usage of Java 8 Consumer interface

Consumer<String> consumer = s->{
   System.out.println(s);
};

consumer.accept("BuggyBread"); // prints BuggyBread

   Like      Feedback     Java 8 Consumer  Consumer interface


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 80. Usage of java.util.function.BiPredicate

BiPredicate<String, String> predicate = (s1, s2) -> (s1.equals(s2));

System.out.println(predicate.test("BUGGY", "BREAD"));

   Like      Feedback     BiPredicate  Java 8 BiPredicate


 Sample 81. Code to get Module name for List class

Module module = java.util.List.class.getModule();
System.out.println(module.getName()); // prints java.base

   Like      Feedback     java 9  java 9 module


 Sample 82. Code to print all packages of a module

Module module = java.util.List.class.getModule();
System.out.println(module.getPackages());

   Like      Feedback     java 9  java 9 modules


 Sample 83. Code to get exports of a particular Module

Module module = java.util.List.class.getModule();
ModuleDescriptor moduleDescriptor = module.getDescriptor();
System.out.println(moduleDescriptor.exports());

   Like      Feedback     java 9  java 9 modules  get exports for a module


 Sample 84. Code to get ModuleDescriptor from a particular Module

Module module = java.util.List.class.getModule();
ModuleDescriptor moduleDescriptor = module.getDescriptor();

   Like      Feedback     java 9  java 9 modules  get ModuleDescriptor for a module


Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner
 Sample 85. Code to get main class in a particular module

Module module = java.util.List.class.getModule();
ModuleDescriptor moduleDescriptor = module.getDescriptor();
System.out.println(moduleDescriptor.mainClass());

   Like      Feedback     java 9  java 9 modules  get main class for a module  get main class for a module in java 9  java module



Subscribe to Java News and Posts. Get latest updates and posts on Java from Buggybread.com
Enter your email address:
Delivered by FeedBurner