Java 8 Programming Interview Questions and Answers (2020) | TechGeekNext >>


Java 8 Programming Interview Questions and Answers (2020)

  1. Q: What are different ways of iterating collection list in Java 8?
  2. Q: How to check if list is empty in Java 8 using Optional, if not null iterate through the list and print the object?
  3. Q: How to sort Collection in Java 8?
  4. Q: How to use map to convert object into Uppercase in Java 8?
  5. Q: How to convert a List of objects to a Map in Java 8 by handling duplicate keys?
  6. Q: How to convert a List of objects to a Map by considering duplicated keys and store them in sorted order?

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:

//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();
		}
	});	
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 post on Java :

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}
































Recommendation for Top Popular Post :