I have a Map with 1000 items and I want to generate a List from the first 500 items of this Map and remove the items that was collected from the Map.
In other words, I want to filter, collect to a List and remove items from a Map.
I'm trying something like that:
final int i = 0; int max = 5; Map<String, Object> map = new HashMap<>(); map.put("ads", "123"); map.put("qwe", "123"); map.put("cvb", "123"); map.put("asd", "123"); map.put("iop", "123"); map.put("jkl", "123"); map.put("yui", "123"); List list = map.entrySet().stream().filter(y -> i++ < max).collect(Collectors.toList()); Expected output:
Map with 2 Values
List with 5 Values
.collector.forEach.entrySet()makes no guarantees about the order of its elements. They are not necessarily the first five you added, unless you're using aLinkedHashMap. But in general, the idea of taking "the first n elements" from a map doesn't make sense, if the order is important perhaps you should use a different data structure.ican't be changed once assigned. So you can't do thisfilter(y -> i++ < max).And even if you didn't declareifinal, local variables must be effectively final in lambdas.