Search Java Code Snippets


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





#Java - Code Snippets for '#List' - 31 code snippet(s) found

 Sample 1. Given a Map with Country Name as key and its capitals as values, Find the name of countries having more than 1 capital ?

Map<String,List<String>> capitals = new HashMap();
capitals.put("United States", Arrays.asList("Washington DC"));
capitals.put("Canada", Arrays.asList("Ottawa"));
capitals.put("South Africa", Arrays.asList("Pretoria", "Cape Down", "Bloemfontein"));
      
for(Map.Entry<String,List<String>> entry: capitals.entrySet()){
   if(entry.getValue().size() > 1){
      System.out.println(entry.getKey());
   }
}

   Like      Feedback     Map of String and List


 Sample 2. 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 3. 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 4. Method to remove duplicates from a Map ( string and List of objects ) by matching the member field of the object.

Map<String,List<ClassInfoBean>> removeDuplicates(Map<String, List<ClassInfoBean>> interfaceMap){
   Map<String, List<ClassInfoBean>> interfaceMapWithoutDuplicate = new HashMap();
      
   for(Map.Entry<String, List<ClassInfoBean>> entry: interfaceMap.entrySet()){
      List<ClassInfoBean> classListWithoutDuplicate = new ArrayList();
      boolean alreadyContain = false;
      for(ClassInfoBean classes: entry.getValue()){
         for(ClassInfoBean classes1: classListWithoutDuplicate){
            if(classes1.name.equalsIgnoreCase(classes.name)){
               alreadyContain = true;
               break;
            }
         }
         if(alreadyContain == false){
            classListWithoutDuplicate.add(classes);
         }
      }
      interfaceMapWithoutDuplicate.put(entry.getKey(), classListWithoutDuplicate);
   }
      
   return interfaceMapWithoutDuplicate;
}

   Like      Feedback     map  map of list of objects  remove duplicates from map  Map.Entry


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. 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 6. 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 7. 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 8. 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 9. 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


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. 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 11. ajax / Jquery call to get the list of check boxes to be disabled.

function disableCheckBox(){
    sendAjaxGetCall(“/resourceUrl?input=”+input) .done(function(data) {
          data = data + '';
          var checkboxToDisable = data.split(",");
          for(int i=0;i < checkboxToDisable.length;i++){
                $(“#”+i).attr("disabled", true);
           }
     }).fail(function(xhr, error) {
           console.log('error: ' + xhr.statusText);
     });
}

   Like      Feedback     jquery  ajax  checkbox   disable checkbox


 Sample 12. Method to remove duplicates from a List of objects by matching the member elements of objects.

List<ClassInfoBean> removeDuplicates(List<ClassInfoBean> listClassInfo){
   Set<ClassInfoBean> set = new HashSet();
   Set<String> url = new HashSet();
   boolean flag = false;
   for(ClassInfoBean cl: listClassInfo){
      if(!url.contains(cl.url)){
         set.add(cl);
         url.add(cl.url);
      }
   }
      
   return new ArrayList(set);
}

   Like      Feedback     list  list of objects  remove duplicates from list


 Sample 13. 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 14. 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 15. 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 16. Method to get specific format files from a directory

private Collection<File> getDocAndTextFiles() {
File directory = new File("C:DocDir");
if (directory.exists() && directory.isDirectory()) {
Collection<File> files = FileUtils.listFiles(directory, new String[] { "doc","txt" }, false);
}
return files;
}

   Like      Feedback     file handling  file  directory  FileUtils.listFiles  fileutils


 Sample 17. 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 18. 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 19. 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


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. 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 21. Usage of SslListener

SslListener sslListener = new SslListener();
sslListener.setHost(addr.getHostName());
sslListener.setPort(addr.getPort());
sslListener.setKeystore(keystore);
sslListener.setPassword(storPass);
sslListener.setKeyPassword(keyPass);
webServer.addListener(sslListener);

   Like      Feedback     SslListener


 Sample 22. 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 23. Code Sample / Example / Snippet of org.apache.spark.network.shuffle.BlockFetchingListener

  public void testNoFailures() throws IOException {

BlockFetchingListener listener = mock(BlockFetchingListener.class);



List<? extends Map<String, Object>> interactions = Arrays.asList(

ImmutableMap.<String, Object>builder()

.put("b0", block0)

.put("b1", block1)

.build()

);



performInteractions(interactions, listener);



verify(listener).onBlockFetchSuccess("b0", block0);

verify(listener).onBlockFetchSuccess("b1", block1);

verifyNoMoreInteractions(listener);

}


   Like      Feedback      org.apache.spark.network.shuffle.BlockFetchingListener


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


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. Code Sample / Example / Snippet of org.apache.bcel.generic.InstructionList

    private void compare(final String name, final Method m) {

final Code c = m.getCode();

if (c == null) {

return; // e.g. abstract method

}

final byte[] src = c.getCode();

final InstructionList il = new InstructionList(src);

final byte[] out = il.getByteCode();

if (src.length == out.length) {

assertArrayEquals(name + ": " + m.toString(), src, out);

} else {

System.out.println(name + ": " + m.toString() + " " + src.length + " " + out.length);

System.out.println(bytesToHex(src));

System.out.println(bytesToHex(out));

for (final InstructionHandle ih : il) {

System.out.println(ih.toString(false));

}

fail("Array comparison failure");

}

}


   Like      Feedback      org.apache.bcel.generic.InstructionList


 Sample 26. Display Elements of a List

List myList = new ArrayList();
      
myList.add("A");
myList.add("B");
myList.add("C");

System.out.println(myList); // Prints [A, B, C]

   Like      Feedback     Print elements of a list


 Sample 27. 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 28. 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


 Sample 29. Given a list of File objects, sort them by their name

public List sortFiles(List<File> files) {
files.sort(new Comparator<File>() {
@Override
public int compare(File file1, File file2) {
return file1.getName().compareTo(file2.getName());
}
});

return files.
}

   Like      Feedback     file


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. 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 31. Initializing a list using factory method in java 9

Usage of List.of()

List<String> countryList = List.of("France","Belgium","Germany");

   Like      Feedback     java 9



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