#Java - Code Snippets for '#Collections' - 46 code snippet(s) found |
|
Sample 1. 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 |
|
|
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. 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 4. 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 5. 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 6. Usage of Apache Commons - ArrayListValuedHashMap | |
|
ListValuedMap<String,String> listValuedMap = new ArrayListValuedHashMap();
listValuedMap.put("United States", "Washington");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("South Africa", "Pretoria");
listValuedMap.put("South Africa", "Cape Town");
listValuedMap.put("South Africa", "Bloemfontein");
System.out.println(listValuedMap); // Values being added to the List and allow even duplicates
|
|
Like Feedback apache commons apache commons collections ArrayListValuedHashMap ListValuedMap |
|
|
Sample 7. 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 8. 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 |
|
|
Sample 9. 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 10. Get all Permutations of List Elements using Apache Commons PermutationIterator | |
|
List<String> list = new ArrayList();
list.add("Washington");
list.add("Nevada");
list.add("California");
PermutationIterator permIterator = new PermutationIterator((Collection) list);
permIterator.forEachRemaining(System.out::print); // prints [Washington, Nevada, California][Washington, California, Nevada][California, Washington, Nevada][California, Nevada, Washington][Nevada, California, Washington][Nevada, Washington, California]
|
|
Like Feedback Permutations of collection elements Permutations of List elements Apache Commons PermutationIterator Iterator Collections .forEachRemaining System.out::print List ArrayList |
|
|
Sample 11. 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 12. 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 13. 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 14. 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 15. 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 16. Sorting an arraylist using Collections.sort | |
|
List<String> myList = new ArrayList<String>();
myList.add("D");
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("E");
System.out.println(myList); // Unsorted
Collections.sort(myList);
System.out.println(myList); // Sorted
|
|
Like Feedback list arraylist collections.sort collections |
|
|
Sample 17. 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 18. 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 |
|
|
Sample 19. Looping through elements of an ArrayList | |
|
public static void main(String[] args){
List list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
for(Integer element: list){
System.out.println(element);
}
}
|
|
Like Feedback arraylist list collections |
|
|
|
Sample 20. Display Elements of a List using Java 8 Consumer | |
|
List myList = new ArrayList();
myList.add("A");
myList.add("B");
myList.add("C");
myList.forEach(System.out::println);
|
|
Like Feedback Print elements of a list java 8 consumer foreach list arraylist collections |
|
|
Sample 21. 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 22. 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 23. 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 24. 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 25. 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 26. 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 27. 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 28. Filtering objects using google.common.base.Predicate | |
|
static Collection<Employee> employeesGreaterThan30(Collection<Employee> employees) {
return filter(employees, new Predicate<Employee>() {
@Override
public boolean apply(Employee employee) {
return employee.getAge() > 30;
}
});
}
|
|
Like Feedback predicate google.common.base.Predicate filter objects alternate for predicate before java 8 collections google guava |
|
|
Sample 29. Order Collection using google.common.collect.Ordering | |
|
Collection<Employee> sortedEmployeess = Ordering.from(new Comparator<Employee>() {
@Override
public int compare(Employee employee1, Employee employee2) {
return employee1.getAge() - employee2.getAge();
}
};).sortedCopy(employees);
|
|
Like Feedback collections sorting collections sorting collections using google library comparator compare method google.common.collect.Ordering google guava |
|
|
|
Sample 30. Usage of Iterator | |
|
Iterator iterator = ReportingEmp.iterator();
while (iterator.hasNext()) {
EmployeeBean eb1 = (EmployeeBean)iterator.next();
EmployeeFactory empFactory = new EmployeeFactory(eb1.getType());
svEmp = empFactory.getFactoryProduct();
allocation += svEmp.getAllocation();
}
|
|
Like Feedback collections Iterator |
|
|
Sample 31. Java 8 Map Merge Example ( Map.merge ) | |
|
Map<String,String> intMap = new HashMap<String,String>();
strMap.put("Key1","Value1");
strMap.put("Key2", "Value2");
String str = strMap.merge("Key1","Value56",(v1,v2)->v1.substring(3).concat(v2));
System.out.println(str); // prints ue1Value56
System.out.println(strMap); // prints {Key2=Value2, Key1=ue1Value56}
|
|
Like Feedback java 8 map.merge map merge hashmap collections |
|
|
Sample 32. Java 8 MapMerge | |
|
Map<String,String> strMap = new HashMap<String,String>();
strMap.put("Key1","Value1");
strMap.put("Key2", "Value2");
String str = strMap.merge("Key4","Value56",(v1,v2)->v1.substring(3).concat(v2));
System.out.println(str); // prints Value56
System.out.println(strMap); // prints {Key2=Value2, Key1=Value1, Key4=Value56}
|
|
Like Feedback java 8 map.merge map merge hashmap collections |
|
|
Sample 33. 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 34. Make a Map entry read only using Apache Commons UnmodifiableMapEntry | |
|
Entry entry = new UnmodifiableMapEntry("Key2", "Value2");
entry.setValue("Value3"); // throws java.lang.UnsupportedOperationException
|
|
Like Feedback read only map entry UnmodifiableMapEntry Apache commons collections |
|
|
|
Sample 35. Print all elements of a ListValuedMap ( Apache Commons ) using forEach and System.out::println | |
|
ListValuedMap<String,String> listValuedMap = new ArrayListValuedHashMap();
listValuedMap.put("United States", "Washington");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("South Africa", "Pretoria");
listValuedMap.put("South Africa", "Cape Town");
listValuedMap.put("South Africa", "Bloemfontein");
listValuedMap.entries().forEach(System.out::println);
|
|
Like Feedback ListValuedMap apache commons System.out::println collections framework map |
|
|
Sample 36. Count elements of a collection matching a Predicate using Apache Commons IterableUtils | |
|
List<String> list = new ArrayList();
list.add("Washington");
list.add("Nevada");
list.add("California");
list.add("New York");
list.add("New Jersey");
// <String> long org.apache.commons.collections4.IterableUtils.countMatches(Iterable<String> input, Predicate<? super String> predicate)
System.out.println(IterableUtils.countMatches(list, p->((String)p).startsWith("N")));
|
|
Like Feedback Apache Commons IterableUtils Apache Commons Predicate Java 8 Count elements of a collection java8 |
|
|
Sample 37. Find the Frequency of a Particular element in a Collection using apache Commons IterableUtils | |
|
List<String> list = new ArrayList();
list.add("Washington");
list.add("Washington");
list.add("Nevada");
System.out.println(IterableUtils.frequency(list, "Washington")); // prints 2
|
|
Like Feedback Frequency of a Particular element in a Collection Apache Commons IterableUtils IterableUtils.frequency |
|
|
Sample 38. 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 39. Usage of Apache Commons CaseInsensitiveMap | |
|
Map<String, String> map = new CaseInsensitiveMap<String, String>();
map.put("US", "Washington");
map.put("us", "Washington DC");
System.out.println(map); // Prints {us=Washington DC} as Keys are case insensitive
|
|
Like Feedback CaseInsensitiveMap Map with Case insensitive keys apache commons apache commons collections |
|
|
|
Sample 40. 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 41. 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 42. 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 43. Code Sample / Example / Snippet of com.mongodb.DBCollection | |
|
private Enumerable<Object> find(DB mongoDb, String filterJson,
String projectJson, List<Map.Entry<String, Class>> fields) {
final DBCollection collection =
mongoDb.getCollection(collectionName);
final DBObject filter =
filterJson == null ? null : (DBObject) JSON.parse(filterJson);
final DBObject project =
projectJson == null ? null : (DBObject) JSON.parse(projectJson);
final Function1<DBObject, Object> getter = MongoEnumerator.getter(fields);
return new AbstractEnumerable<Object>() {
public Enumerator<Object> enumerator() {
final DBCursor cursor = collection.find(filter, project);
return new MongoEnumerator(cursor, getter);
}
};
}
|
|
Like Feedback com.mongodb.DBCollection |
|
|
Sample 44. 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 45. Display elements of a List using For loop | |
|
List myList = new ArrayList();
myList.add("A");
myList.add("B");
myList.add("C");
for(String str:myList){ // prints A B C
System.out.println(str);
}
|
|
Like Feedback Print elements of a list for loop arraylist list collections |
|
|
Sample 46. Display elements of a List using For Loop and index | |
|
List myList = new ArrayList();
myList.add("A");
myList.add("B");
myList.add("C");
for(int index=0;index < myList.size(); index++){
System.out.println(myList.get(index));
}
|
|
Like Feedback Print elements of a list arraylist list collections for loop |
|
|