Share

Search Java Code Snippets


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





#Java - Code Snippets for '#Set' - 46 code snippet(s) found

 Sample 1. 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 2. 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 3. Count number of collection elements using Lambda Expressions

// 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);

// Use the stream method count to see if all elements fulfils the Predicate.

System.out.println(intSet.stream().count); // Prints 4.

   Like      Feedback     lambda expression   collections   set  hashset  generics  predicate


 Sample 4. Class bean with getter , setter and constructor

public class Employee {
public String name;
public int age;
public int salary;

Employee(String name, int age, int salary) {
this.name = name;
this.age = age;
this.salary = salary;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public int getSalary() {
return salary;
}

public void setSalary(int salary) {
this.salary = salary;
}
}

   Like      Feedback     bean   pojo   plain java objects   getters   setters   getters nd setters   classes   class   constructor   parameterized constructor  this keyword


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. Find, if all elements of a collection matches the specified condition ( Using Lambda expressions )
Admin
info@buggybread.com
// 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);

// Specify the Predicate or the Condition using Lambda expressions

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

// Use the stream method allMatch to see if all elements fulfils the Predicate.

   Like      Feedback     lambda expression   collections   set  hashset  generics  predicate


 Sample 6. Find, if any element of the collection matches the specified condition ( Using Lambda Expressions )
Admin
info@buggybread.com
// 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);

// Specify the Predicate or the Condition using Lambda expressions

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

// Use the stream method anyMatch to see if all elements fulfils the Predicate.

System.out.println(intSet.stream().anyMatch(moreThan2Pred)); // Prints True.

   Like      Feedback     lambda expression   collections   set  hashset  generics  predicate


 Sample 7. Find, if no element of the collection matches the specified condition ( Inverse of anyMatch )

// 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);

// Specify the Predicate or the Condition using Lambda expressions

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

// Use the stream method noneMatch to see if all elements fulfils the Predicate.

System.out.println(intSet.stream().noneMatch(moreThan2Pred)); // Prints False.

   Like      Feedback     lambda expression   collections   set  hashset  generics  predicate


 Sample 8. Find the Average of all collection elements using Lambda Expressions

// 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);

// Use the stream and Collector to find the average of all elements.

System.out.println(intSet.stream().collect(Collectors.averagingInt(p->((Integer)p))));  Prints 2.5

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collector


 Sample 9. Group Elements by even or Odd using Lambda Expressions

// 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);

// Use the stream and Collector to Group by Even and Odd

System.out.println(intSet.stream().collect(Collectors.groupingBy(p->((Integer)p)%2)));  Prints {0=[2, 4], 1=[1, 3]}

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.groupingBy


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. Sum all collection elements using Lambda Expressions

// 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);

// Use the stream and collectors to sum all elements.

System.out.println(intSet.stream().collect(Collectors.summingInt(p->(Integer)p)));

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.groupingBy


 Sample 11. Populate a List using Set elements and 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);

// Use the stream and collectors to get List out of Set

List li = intSet.stream().collect(Collectors.toList());
System.out.println(li); // Prints [1, 2, 3, 4]

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.toList


 Sample 12. Get the complete Summary of Collection Elements using Lambda Expressions

// Populate a List using Set elements.

// 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);

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

System.out.println(intSet.stream().collect(Collectors.summarizingInt(p->((Integer)p)))); // Prints IntSummaryStatistics{count=4, sum=10, min=1, average=2.500000, max=4}

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors   Collectors.summarizingInt


 Sample 13. Create a Map using Set elements 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);

// Use the stream and collectors to get a Map out of Set 

System.out.println(intSet.stream().collect((Collectors.toMap(p->(Integer)p,q->((Integer)q)*500)))); // Prints {1=500, 2=1000, 3=1500, 4=2000} 

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   collectors


 Sample 14. Get count of elements greater than 1 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);

// Use Stream, Predicate and Filter to get the count of elements more than 1

System.out.println(intSet.stream().filter(moreThan2Pred).count()); // Prints 3

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream   predicate   filter


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. Get the Maximum number out of the Integer List, using Lambda Expression

// Declare and Initialize the Collection

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

// Add Elements

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


System.out.println(intList.stream().reduce(Math::max).get()); // Prints 1

   Like      Feedback     lambda expression   collections   set  hashset  generics  stream  reducer   Math::max


 Sample 16. Method to convert all elements of a collection ( Set ) to lower case.

Set<String> convertLowerCase(Set<String> set){
   Set<String> newSet = new HashSet();
   for(String s: set){
      newSet.add(s.toLowerCase());
   }
      
   return newSet;
}

   Like      Feedback     string  collections  set  .tolowercase()


 Sample 17. Method to get a map of words and their count by passing in the string

Map<String,Integer> wordCountMap = new TreeMap();
String[] words = text.split(" ");
Set<Integer> countSet;
for(String word: words) {
if(wordCountMap.containsKey(word.toLowerCase())){
wordCountMap.put(word.toLowerCase(), wordCountMap.get(word.toLowerCase()).intValue() + 1);
} else {
wordCountMap.put(word.toLowerCase(), 1);
}
}

countSet = new TreeSet(Collections.reverseOrder());
countSet.addAll(wordCountMap.values());

for(Integer inte: countSet) {
for(Entry<String,Integer> entry: wordCountMap.entrySet()){
if(entry.getValue() == inte) {
System.out.println(entry);
}
}
}

   Like      Feedback     map  word count  map of string and integer  containsKey  string split  treeset  Collections.reverseOrder  set addAll   entry


 Sample 18. Sorting elements of a set using TreeSet

Set<String> mySet = new HashSet<String>();
mySet.add("D");
mySet.add("A");
mySet.add("B");
mySet.add("C");
mySet.add("E");

System.out.println(mySet); // May be Sorted but sorting is not guaranteed

mySet = new TreeSet<String>(mySet);

System.out.println(mySet); // Sorted

   Like      Feedback     sorting  collections  treeset  set  hashset


 Sample 19. 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 20. 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 21. 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 22. Get a unmodifiable / read only Set

Set<String> modifiableSet = Sets.newHashSet();

modifiableSet.add("New York");
modifiableSet.add("Washington");
modifiableSet.add("Georgia");

Set<String> unmodifiableSet = Collections.unmodifiableSet(modifiableSet);

   Like      Feedback     collections  set  unmodifiable set   unmodifiableset   Collections.unmodifiableSet


 Sample 23. 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 24. Usage of Apache Commons - HashSetValuedHashMap

SetValuedMap<String,String> setValuedMap = new HashSetValuedHashMap();
setValuedMap.put("United States", "Washington");
setValuedMap.put("Canada", "Ottawa");
setValuedMap.put("Canada", "Ottawa");
setValuedMap.put("South Africa", "Pretoria");
setValuedMap.put("South Africa", "Cape Town");
setValuedMap.put("South Africa", "Bloemfontein");
      
System.out.println(setValuedMap); // Values being added to the Set and hence doesn't allow duplicates

   Like      Feedback     apache commons   apache commons collections  apache commons map   HashSetValuedHashMap  SetValuedMap


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. Usage of Apache Commons CharSet

String str = new String("Hello World");
CharSet charSet = CharSet.getInstance(str);
System.out.println(charSet.contains('W')); // prints true
System.out.println(charSet.contains('w')); // prints false

   Like      Feedback     CharSet  Apache Commons  CharSet Example  CharSet Sample  String  characters


 Sample 26. Remove characters from the String using CharSetUtils

String str = new String("Hello World"); 
String newStr = CharSetUtils.delete(str, "abcde");
System.out.println(newStr); // prints Hllo Worl

   Like      Feedback     Remove characters from the String  String  CharSetUtils  Apache Commons


 Sample 27. Remove Numbers from a String using CharSetUtils (Apache Commons)

String str = new String("1H4ello1 World2"); 

String newStr = CharSetUtils.delete(str, "1234567890");

System.out.println(newStr); // prints Hello World

   Like      Feedback     Apache Commons  CharSetUtils   Remove Numbers from String


 Sample 28. Remove special characters from a String using CharSetUtils ( Apache Commons )

String str = new String("What's Up ?"); 

String newStr = CharSetUtils.delete(str, "'?");

System.out.println(newStr); // prints Whats Up

   Like      Feedback     Apache Commons  CharSetUtils  Remove characters from String


 Sample 29. Check if the String contains specified characters using CharSetUtils (Apache Commons)

System.out.println(CharSetUtils.containsAny("Whats Up ?", "W")); // Prints true as the String contains character W  System.out.println(CharSetUtils.containsAny("Whats Up ?", "YZ")); // Prints false as the String doesn't contain character Y or Z

   Like      Feedback     CharSetUtils (Apache Commons)  Check if String contains characters


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. Print the characters that exist in the specified String using CharSetUtils ( Apache Commons )

System.out.println(CharSetUtils.keep("Whats Up ?", "Watch")); // Prints Wat as only those characters matches in the String 

   Like      Feedback     Characters that exist in String  CharSetUtils ( Apache Commons )


 Sample 31. Apache Commons MultiSet Example

MultiSet<String> multiSet = new HashMultiSet(); 
multiSet.add("Albama");
multiSet.add("Albama");
multiSet.add("Albama");
      
System.out.println(multiSet); // Prints [Albama:3]

   Like      Feedback     Set with duplicate values  MultiSet  Apache Commons Collections


 Sample 32. Create an UnmodifiableMultiSet ( Read only set allowing multiple values ) using Apache Commons

MultiSet<String> multiSet = new HashMultiSet(); 
multiSet.add("Albama");
multiSet.add("Albama");
multiSet.add("Albama");

System.out.println(multiSet); // Prints [Albama:3]
      
UnmodifiableMultiSet<String> unmodifiablemultiSet = (UnmodifiableMultiSet<String>) MultiSetUtils.unmodifiableMultiSet(multiSet);

unmodifiablemultiSet.add("Albama"); // throws java.lang.UnsupportedOperationException

   Like      Feedback     UnmodifiableMultiSet  Apache Commons Collections  Set  MultiSet


 Sample 33. Usage of org.apache.commons.validator.ValidatorAction

ValidatorAction va = new ValidatorAction();
va.setName(action);
va.setClassname("org.apache.commons.validator.ValidatorTest");
va.setMethod("formatDate");
va.setMethodParams("java.lang.Object,org.apache.commons.validator.Field");

FormSet fs = new FormSet();
Form form = new Form();
form.setName("testForm");
Field field = new Field();
field.setProperty(property);
field.setDepends(action);
form.addField(field);
fs.addForm(form);

resources.addValidatorAction(va);
resources.addFormSet(fs);

   Like      Feedback     Apache Commons  ValidatorAction  FormSet


 Sample 34. Code Sample / Example / Snippet of java.time.zone.ZoneOffsetTransition

    public static ZonedDateTime ofLocal(LocalDateTime localDateTime, ZoneId zone, ZoneOffset preferredOffset) {

Objects.requireNonNull(localDateTime, "localDateTime");

Objects.requireNonNull(zone, "zone");

if (zone instanceof ZoneOffset) {

return new ZonedDateTime(localDateTime, (ZoneOffset) zone, zone);

}

ZoneRules rules = zone.getRules();

List<ZoneOffset> validOffsets = rules.getValidOffsets(localDateTime);

ZoneOffset offset;

if (validOffsets.size() == 1) {

offset = validOffsets.get(0);

} else if (validOffsets.size() == 0) {

ZoneOffsetTransition trans = rules.getTransition(localDateTime);

localDateTime = localDateTime.plusSeconds(trans.getDuration().getSeconds());

offset = trans.getOffsetAfter();

} else {

if (preferredOffset != null && validOffsets.contains(preferredOffset)) {

offset = preferredOffset;

} else {

offset = Objects.requireNonNull(validOffsets.get(0), "offset"); // protect against bad ZoneRules

}

}

return new ZonedDateTime(localDateTime, offset, zone);

}


   Like      Feedback      java.time.zone.ZoneOffsetTransition


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. Code Sample / Example / Snippet of java.time.ZoneOffset

public static LocalTime now(Clock clock) {

Objects.requireNonNull(clock, "clock");

final Instant now = clock.instant(); // called once

ZoneOffset offset = clock.getZone().getRules().getOffset(now);

long localSecond = now.getEpochSecond() + offset.getTotalSeconds(); // overflow caught later

int secsOfDay = (int) Math.floorMod(localSecond, SECONDS_PER_DAY);

return ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + now.getNano());

}

   Like      Feedback      java.time.ZoneOffset


 Sample 36. Code Sample / Example / Snippet of java.sql.ResultSet

  public String prepareBindExecute(HrConnection state) throws SQLException {

Connection con = state.con;

Statement st = null;

ResultSet rs = null;

String ename = null;

try {

final PreparedStatement ps =

con.prepareStatement("select name from emps where empid = ?");

st = ps;

ps.setInt(1, state.id);

rs = ps.executeQuery();

rs.next();

ename = rs.getString(1);

} finally {

close(rs, st);

}

return ename;

}


   Like      Feedback      java.sql.ResultSet


 Sample 37. Code Sample / Example / Snippet of org.apache.calcite.plan.RelTraitSet

    public RelNode convert(RelNode rel) {

final Sort sort = (Sort) rel;

final RelTraitSet traitSet =

sort.getTraitSet().replace(out)

.replace(sort.getCollation());

return new MongoSort(rel.getCluster(), traitSet,

convert(sort.getInput(), traitSet.replace(RelCollations.EMPTY)),

sort.getCollation(), sort.offset, sort.fetch);

}


   Like      Feedback      org.apache.calcite.plan.RelTraitSet


 Sample 38. Code Sample / Example / Snippet of java.sql.ResultSetMetaData

  private void output(ResultSet resultSet, PrintStream out)

throws SQLException {

final ResultSetMetaData metaData = resultSet.getMetaData();

final int columnCount = metaData.getColumnCount();

while (resultSet.next()) {

for (int i = 1;; i++) {

out.print(resultSet.getString(i));

if (i < columnCount) {

out.print(", ");

} else {

out.println();

break;

}

}

}

}


   Like      Feedback      java.sql.ResultSetMetaData


 Sample 39. Code Sample / Example / Snippet of com.datastax.driver.core.ResultSet

  public String prepareBindExecute(HrConnection state) throws SQLException {

Connection con = state.con;

Statement st = null;

ResultSet rs = null;

String ename = null;

try {

final PreparedStatement ps =

con.prepareStatement("select name from emps where empid = ?");

st = ps;

ps.setInt(1, state.id);

rs = ps.executeQuery();

rs.next();

ename = rs.getString(1);

} finally {

close(rs, st);

}

return ename;

}


   Like      Feedback      com.datastax.driver.core.ResultSet


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. Code Sample / Example / Snippet of org.apache.calcite.sql.SqlSetOption

  private static void checkSqlSetOptionSame(SqlNode node) {

SqlSetOption opt = (SqlSetOption) node;

SqlNode[] sqlNodes = new SqlNode[opt.getOperandList().size()];

SqlCall returned = opt.getOperator().createCall(

opt.getFunctionQuantifier(),

opt.getParserPosition(),

opt.getOperandList().toArray(sqlNodes));

assertThat((Class) opt.getClass(), equalTo((Class) returned.getClass()));

SqlSetOption optRet = (SqlSetOption) returned;

assertThat(optRet.getScope(), is(opt.getScope()));

assertThat(optRet.getName(), is(opt.getName()));

assertThat(optRet.getFunctionQuantifier(), is(opt.getFunctionQuantifier()));

assertThat(optRet.getParserPosition(), is(opt.getParserPosition()));

assertThat(optRet.getValue(), is(opt.getValue()));

assertThat(optRet.toString(), is(opt.toString()));

}


   Like      Feedback      org.apache.calcite.sql.SqlSetOption


 Sample 41. 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


 Sample 42. 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 43. Code Sample / Example / Snippet of org.apache.ace.range.SortedRangeSet

    private void verifyStoreContents(final LogStoreImpl store, final int count, Writer... writers) throws IOException {

List<Descriptor> descriptors = store.getDescriptors();



long expectedID = 0;

for (Descriptor desc : descriptors) {

SortedRangeSet rangeSet = desc.getRangeSet();

RangeIterator rangeIter = rangeSet.iterator();



while (rangeIter.hasNext()) {

long id = rangeIter.next();



Event expectedEntry = null;

for (int i = 0; (expectedEntry == null) && i < writers.length; i++) {

expectedEntry = writers[i].m_written.remove(id);

}

assertNotNull(expectedEntry, "Event ID #" + id + " never written?!");

assertEquals(expectedEntry.getID(), expectedID++, "Entry ID mismatch?!");

}

}

}


   Like      Feedback      org.apache.ace.range.SortedRangeSet


 Sample 44. Code Sample / Example / Snippet of org.apache.felix.framework.capabilityset.SimpleFilter

    private static boolean matchMandatoryAttrbute(String attrName, SimpleFilter sf)

{

if ((sf.getName() != null) && sf.getName().equals(attrName))

{

return true;

}

else if (sf.getOperation() == SimpleFilter.AND)

{

List list = (List) sf.getValue();

for (int i = 0; i < list.size(); i++)

{

SimpleFilter sf2 = (SimpleFilter) list.get(i);

if ((sf2.getName() != null)

&& sf2.getName().equals(attrName))

{

return true;

}

}

}

return false;

}


   Like      Feedback      org.apache.felix.framework.capabilityset.SimpleFilter


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

import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.context.annotation.Bean;
import org.springframework.web.multipart.MultipartResolver;

@EnableWebMvc
@Configuration
public class Application extends WebMvcConfigurerAdapter {
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(500000);
return multipartResolver;
}
}

   Like      Feedback     Usage of MultipartResolver  multipartResolver.setMaxUploadSize(500000)  Setting max file size using Spring multipartResolver


 Sample 46. Write a Program that gets a set of numbers , filters out the non prime numbers , calculate the factorial of each prime number and then finds the average of all factorials using Lambda expressions

public class BuggyBread1 {
   
   public static void main(String args[]) {
      
      // 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);
      intSet.add(5);

      double averageOfNonPrimeFactorials = intSet.stream().filter(p->checkIfPrime(p)).collect(Collectors.averagingInt(p->calculateFactorial(p)));
      
      System.out.println(averageOfNonPrimeFactorials );
   }
   
   static private boolean checkIfPrime(int num){
      for(int count=2;count < num;count++){
         if(num % count == 0){
            return false;
         }
      }
      return true;
   }
   
   static private int calculateFactorial(int num){
      int factorial = 1;
      for(int count=num;count > 0;count--){
         factorial = factorial * count;
      }
      return factorial;
   }
}

   Like      Feedback     java 8  lambda expressions  lambda  filter  Collectors  factorial  prime number



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



comments powered by Disqus