Conversions Using Java Streams

Conversions of various data structures using Streams

- int []array -> Integer ArrayList

List<Integer> l=Arrays.stream(nums).boxed().toList();

This code will create a unmodifiable list as Arrays.toList creates a wrapper list over the array.Exactly as array’s length cannot be change the lengthof this list cannot be changed too. Hence methods like remove() will give Unsupported Operation exception

  • To solve this,just create a “real” new list
List<Integer> l=new ArrayList(Arrays.stream(nums).boxed().toList());

- Integer ArrayList -> int []array

int[] example1 = list.stream().mapToInt(i->i).toArray();
// OR
int[] example2 = list.stream().mapToInt(Integer::intValue).toArray();

Fetching particular key from Hashmap based on value

final Integer r1=r;
	     Integer t=map.entrySet().stream()
.filter(e -> e.getValue().equals(r1))
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);

final is needed otherwise you will get error *Line 11: error: local variables referenced from a lambda expression must be final or effectively final .filter(e -> e.getValue().equals(r))

Edit this page on GitHub