Adblocker detected! Please consider whitelist or disable this site.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

To keep the site operating, we need funding, and practically all of it comes from internet advertising.

If you still want to continue, Please add techgeeknext.com to your ad blocking whitelist or disable your adblocking software.

×
Frequently asked Java 8 Collection Programming Interview Questions (2022) | TechGeekNxt >>





Java 8 Programming Interview Questions and Answers (2022)

  1. What are different ways of iterating collection list in Java 8?
  2. How to check if list is empty in Java 8 using Optional, if not null iterate through the list and print the object?
  3. How to sort Collection in Java 8?
  4. How to use map to convert object into Uppercase in Java 8?
  5. How to convert a List of objects to a Map in Java 8 by handling duplicate keys?
  6. How to convert a List of objects to a Map by considering duplicated keys and store them in sorted order?
  7. What is the best way to convert a primitive Array to a List in Java 8?
  8. How to sort arrays of primitive types in descending order in Java 8?
  9. How to concatenate List of String/Integer Objects using some separator in Java8?
  10. How to count each element/word from the String ArrayList in Java8?
  11. How to find only duplicate elements with its count from the String ArrayList in Java8?

What are different ways of iterating collection list in Java 8?
Ans:

List<String> notes = new ArrayList<>();
	notes.add("note1");
	notes.add("note2");
	notes.add("note3");
	notes.add("note4");
	notes.add("note5");

	//Using lambda expression
	//Output : note1,note2,note3,note4,note5
	notes.forEach(note->System.out.println(note));

	//Output : note3
	notes.forEach(note->{
		if("note3".equals(note)){
			System.out.println(note);
		}
	});

	//Using Stream and filter
	//Output : note2
	notes.stream()
		.filter(s->s.contains("note2"))
		.forEach(System.out::println);

	//Using method reference
	//Output : note1,note2,note3,note4,note5
	notes.forEach(System.out::println);

Q: How to check if list is empty in Java 8 using Optional, if not null iterate through the list and print the object?
Ans:


Optional.ofNullable(noteLst)
            .orElseGet(Collections::emptyList) // creates empty immutable list: [] in case noteLst is null
            .stream().filter(Objects::nonNull) //loop throgh each object and consider non null objects
            .map(note -> Notes::getTagName) // method reference, consider only tag name
            .forEach(System.out::println); // it will print tag names

Q: How to sort Collection in Java 8?
Ans:

Prior to Java 8:
//Older way to sort, before java 8
		noteLst.sort(new Comparator<Notes>() {
		@Override
		public int compare(Notes n1, Notes n2) {
			return n1.getId()-n2.getId();
		}
	});	
In Java 8:
public class TestNotes {

    public static void main(String[] args) {

        List<Notes> noteLst = new ArrayList<>();
        noteLst.add(new Notes(1, "aa", 11));
        noteLst.add(new Notes(3, "cc", 33));
        noteLst.add(new Notes(4, "bb", 44));
		noteLst.add(new Notes(2, "dd", 34));
        noteLst.add(new Notes(5, "zz", 32));

		// java 8 sort according to id 1,2,3,4,5
        noteLst.sort((n1, n2)->n1.getId()-n2.getId());

		//java 8 print the notes using lamda
		noteLst.forEach((note)->System.out.println(note));
    }
}
//Output 

Notes [id=1, tagName=aa, tagId=11]
Notes [id=2, tagName=dd, tagId=34]
Notes [id=3, tagName=cc, tagId=33]
Notes [id=4, tagName=bb, tagId=44]
Notes [id=5, tagName=zz, tagId=32]

Q: How to use map to convert object into Uppercase in Java 8?
Ans:

//Older way to convert object to uppercase
		List<String> names = Arrays.asList("aa", "bb", "cc", "dd");

        List<String> uppercaseNames = new ArrayList<>();
        for (String name : names) {
            uppercaseNames.add(name.toUpperCase());
        }
       // In Java 8
        List<String> nameLst = names.stream().map(String::toUpperCase).collect(Collectors.toList());
        System.out.println(nameLst); //output- [AA, BB, CC, DD]

Take a look at our Suggested Posts :

Q: How to convert a list of objects to a Map in Java 8 by handling duplicate keys?
Ans:

public class Notes {

    private int id;
    private String tagName;
    private long tagId;

    public Notes(int id, String tagName, long tagId) {
        Id = id;
        this.tagName = tagName;
        this.tagId = tagId;
    }

   // getters and setters
}
public class TestNotes {

    public static void main(String[] args) {

        List<Notes> noteLst = new ArrayList<>();
        noteLst.add(new Notes(1, "note1", 11));
        noteLst.add(new Notes(2, "note2", 22));
        noteLst.add(new Notes(3, "note3", 33));
        noteLst.add(new Notes(4, "note4", 44));
        noteLst.add(new Notes(5, "note5", 55));

        noteLst.add(new Notes(6, "note4", 66));

//use third mergeFunction argument (oldValue, newValue) -> oldValue solved the duplicated key issue by considering old value
        Map<String, Long> notesRecords = noteLst.stream().collect(
                Collectors.toMap(Notes::getTagName, Notes::getTagId,
                        (oldValue, newValue) -> oldValue
                )
        );

        System.out.println("Notes : " + notesRecords);
    }
}
//Output - for (oldValue, newValue) -> oldValue, it took old value note4=44
Notes : {note1=11, note2=22, note3=33, note4=44, note5=55}
//Output - for (oldValue, newValue) -> newValue, it took new value note4=66
Notes : {note1=11, note2=22, note3=33, note4=66, note5=55}

Q: How to convert a List of objects into a Map by considering duplicated keys and store them in sorted order?
Ans:

Consider above Example with Notes object and TestNotes Main class.

public class TestNotes {

    public static void main(String[] args) {

        List<Notes> noteLst = new ArrayList<>();
        noteLst.add(new Notes(1, "note1", 11));
        noteLst.add(new Notes(2, "note2", 22));
        noteLst.add(new Notes(3, "note3", 33));
        noteLst.add(new Notes(4, "note4", 44));
        noteLst.add(new Notes(5, "note5", 55));

        noteLst.add(new Notes(6, "note4", 66));


        Map<String, Long> notesRecords = noteLst.stream()
		 .sorted(Comparator.comparingLong(Notes::getTagId).reversed()) // sorting is based on TagId 55,44,33,22,11
		.collect(
                Collectors.toMap(Notes::getTagName, Notes::getTagId,
                        (oldValue, newValue) -> oldValue, // consider old value 44 for dupilcate key
						LinkedHashMap::new           // it keeps order           
                )
        );

        System.out.println("Notes : " + notesRecords);
    }
}
//Output - for (oldValue, newValue) -> oldValue, it took old value note4=44
Notes : {note5=55, note4=44, note3=33, note2=22, note1=11}

Q: What is the best way to convert a primitive Array to a List in Java 8?
Ans:

Prior to Java 8:
int[] nums = {1, 2, 3, 4, 5, 6, 7};

List<Integer> numLst = new ArrayList<>();
for (int n : nums)
{
 numLst.add(n);
}
In Java 8:
In Java 8, we could do the conversion of the Stream using boxing.
//using Arrays.stream() sequential stream with boxed
List<Integer> numsLst = Arrays.stream(nums).boxed().collect(Collectors.toList());

//OR
//By using IntStream.boxed(), convert each element of the stream to an Integer ().
List<Integer> numsLst = IntStream.of(nums).boxed().collect(Collectors.toList());

Q: How to sort int arrays of primitive types in descending order in Java 8?
Ans:

int numArr = new int[]{1,2,3,4,5};

int[] sortedNumArr = Arrays.stream(numArr).boxed().sorted(Collections.reverseOrder())
.mapToInt(Integer::intValue).toArray();

Q: How to concatenate List of String/Integer Objects using some separator in Java8?
Ans:

//input
List<String> str = Arrays.asList("Welcome", "to", "TechGeekNext");

String jonStr = str.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(" - "));
//output
System.out.println(jonStr);
Output:
Welcome - to - TechGeekNext

Q: How to count each element/word from the String ArrayList in Java8?
Ans:

List<String> names = Arrays.asList("AA", "BB", "AA", "CC");
Map<String,Long> namesCount = names
                          .stream()
                          .collect(
                           Collectors.groupingBy(
                             Function.identity()
                           , Collectors.counting()
                           ));
System.out.println(namesCount);
Output:
{CC=1, BB=1, AA=2}

Q: How to find only duplicate elements with its count from the String ArrayList in Java8?
Ans:

List<String> names = Arrays.asList("AA", "BB", "AA", "CC");
Map<String,Long> namesCount = names
                             .stream()
				             .filter(x->Collections.frequency(names, x)>1)
				             .collect(Collectors.groupingBy
				             (Function.identity(), Collectors.counting()));
System.out.println(namesCount);
Output:
{AA=2}












Recommendation for Top Popular Post :