Cool things I found out in Java

Noobnoob
2 min readMay 12, 2021

--

So the boring for loop can be replaced by If the index is necessary with the forEach

IntStream.rangeClosed(0, s.length() - 10).forEach(i->{
});

How is Collection implemented in Java?

The Map is the only interface that doesn’t inherit from the Collection interface but it is part of the Collections framework. All the collections framework interfaces are present in java.util package.

Very Stupid question, how to sort a hashset?
Can you?

Why use queue for bfs and stack for dfs?

Stream() vs ParallelStream():

Stream uses a single pipeline so no use of multithreading but it gives an option to manipulate the data through a pipeline.

ParallelStream uses multithreading so the the streams should be stateless.

foreach vs foreachOrdered()

doesn’t make sense to use parallelStream.foreachOrdered() but if there is some other operation in between like map or sth else, it will be helpful.

Merge sort is stable

ConcurrentModificaitonException

You must be thinking about how the Iterator checks for the modification, this is because the implementation of Iterator is present in AbstractList class where an int variable, modCount is present with the definition. The modCount variable provides the number of times the list size is changed. Every next() call used the modCount variable to check for any modifications in a function checkForComodification().

List<Employee> set=new ArrayList<>();
set.add(new Employee("Crish",1));
set.add(new Employee("Ram",50));
set.add(new Employee("Tom",2));
set.add(new Employee("John",31));
Iterator<Employee> itr = set.iterator();
while (itr.hasNext()){
Employee next = itr.next();
System.out.println(next);
if(next.empId==2){
set.remove(next);
}
}

why does this code does not throw concurrentModificaiton exception.

Reason: when the second last element is accessed, cursor used to get current position will be at size-1;

Now when we remove the secondlast element, the size id reduced by one and when the hasnext() is called, it returns false:

But Still, how does it check for modification in other cases?

modcount is incremented every time we make a change. expectedmodcount is set at the beginning when the iterator is taken.

--

--

Noobnoob
Noobnoob

No responses yet