Convert arraylist loop with java 8 foreach

how to iterate arraylist in java using for each loop
java 8 foreach list of objects
how to iterate arraylist in java using for loop
java foreach arraylist of objects
java list foreach
how to iterate list inside list in java 8
java 8 foreach multiple statements
java 8 foreach add to list

Need to convert for loop (Java 6) to foreach (Java 8)

 List<CustomFormAttributeLite> custFormAttrLiteList = ArrayList ... ;
Map<String,Map<Long,Long>> customNameId = new HashMap<String, Map<Long,Long>>();
Map<Long,Long> custNameAndType = null;

for(CustomFormAttributeLite customFormAttributeLite:custFormAttrLiteList) {

    custNameAndType = new HashMap<Long,Long>();
    custNameAndType.put(customFormAttributeLite.getId(), customFormAttributeLite.getFieldType());

    customNameId.put(customFormAttributeLite.getName(), custNameAndType);
}

I am trying something like that.. But not sure how to do that

custFormAttrLiteList.forEach((customFormAttributeLite)->
                custNameAndType = new HashMap<Long,Long>();
                custNameAndType.put(customFormAttributeLite.getId(), customFormAttributeLite.getFieldType());

                customNameId.put(customFormAttributeLite.getName(), custNameAndType);
            );

You can also use Collectors#groupingBy for this purpose. First group by the name field then group by id and fieldType.

List<CustomFormAttributeLite> custFormAttrLiteList = new ArrayList<>();

Map<String,Map<Long,Long>> customNameId = custFormAttrLiteList.stream()
                        .collect(Collectors.groupingBy(CustomFormAttributeLite::getName,
                         Collectors.toMap(CustomFormAttributeLite::getId, CustomFormAttributeLite::getFieldType)));

If the names are not unique, the result won't be the same as you expect so in that case we need to use Collectors.toMap and use the mergeFunction to retain only the second non-unique entry:

Map<String,Map<Long,Long>> customNameIdNonUnique = custFormAttrLiteList.stream()
                    .collect(Collectors.toMap(CustomFormAttributeLite::getName, //key mapper function
                     (obj) -> {Map<Long,Long> map = new HashMap<>(); map.put(obj.getId(), obj.getFieldType()); return map;}, //value mapper function
                     (key1, key2)-> key2)); //retaining only the second entry 

As a test I've used the following dataset, to test both these solutions:

CustomFormAttributeLite c1 = new CustomFormAttributeLite("foo", 123L, 123L);
CustomFormAttributeLite c2 = new CustomFormAttributeLite("foo", 124L, 125L);
CustomFormAttributeLite c3 = new CustomFormAttributeLite("bar", 125L, 126L);
CustomFormAttributeLite c4 = new CustomFormAttributeLite("bar", 125L, 126L);

The second solution yielded the output:

{bar={125=126}, foo={124=125}}

How to iterate through ArrayList of objects in Java, There are five ways to loop ArrayList. For Loop; Advanced for loop; List Iterator; While Loop; Java 8 Stream. 1. Iterate through ArrayList with  2. ArrayList forEach() example. Java program to iterate an arraylist using forEach() method. This example iterate a list and print the lowercase of strings in the list. Notice how we are passing a lambda expression to the forEach() statement in second iteration.

You can use only final variables inside for-each lambda expression. So try like this:

final Map<String,Map<Long,Long>> customNameId = new HashMap<String, Map<Long,Long>>();
custFormAttrLiteList.forEach((customFormAttributeLite)-> {
                Map<Long,Long> custNameAndType = new HashMap<Long,Long>();
                custNameAndType.put(customFormAttributeLite.getId(), customFormAttributeLite.getFieldType());

                customNameId.put(customFormAttributeLite.getName(), custNameAndType);
            });

Convert arraylist loop with java 8 foreach, You can also use Collectors#groupingBy for this purpose. First group by the name field then group by id and fieldType. ArrayList forEach() method in Java The forEach() method of ArrayList used to perform the certain operation for each element in ArrayList. This method traverses each element of the Iterable of ArrayList until all elements have been Processed by the method or an exception is raised.

I highly recommend you to avoid mutating state of a collection in forEach. Collect the data using .collect(...) instead.

First create a method (either static or dynamic) for mapping a CustomFormAttributeLite to Map<Long,Long>:

Map<Long,Long> mapToNameAndType(CustomFormAttributeLite attribute){
    Map<Long, Long> map = new HashMap<>();
    map.put(attribute.getId(), attribute.getFieldType());
    return map;
}

Then you can simply collect the data into a new Map using Collectors.toMap():

Map<String, Map<Long, Long>> customNameId = 
    custFormAttrLiteList.stream()                                                                         
                        .collect(toMap(CustomFormAttributeLite::getName,this::mapToNameAndType));

Java Loop Through List, As of Java 8, we can use the forEach method as well a 8, we can use the forEach method as well as the iterator class to loop over an ArrayList. How to compare two ArrayLists in Java · How to convert list to array in Java  ArrayList index starts from 0, so we initialized our index variable i with 0 and looped until it reaches the ArrayList size – 1 index. Inside the loop we print the elements of ArrayList using the get method.

10 Examples of forEach() method in Java 8, From Java 8 onward, you can iterate over a List or any Collection without using any loop in Java. The new Stream class provides a forEach() method, which can be used to loop over all or List<String> alphabets = new ArrayList<>(Arrays. one type to another e.g. in our first example we are using map() to transform a list​  The following example shows how to iterate over an ArrayList using. Java 8 forEach and lambda expression. iterator(). iterator() and Java 8 forEachRemaining() method. listIterator(). Simple for-each loop. for loop with index.

Java forEach tutorial - forEach on Java lists, maps, sets, Java forEach tutorial shows how to use Java 8 forEach() method. public static void main(String[] args) { List<String> items = new ArrayList<>(); items.add("coins​"); In this example, we iterate over a list of strings with forEach() . We use Arrays.stream() method to transform the array into a stream. filter(s -> s.contains("java")). forEach((string) -> { System.out.println("Content: " + string); }); } NetBeans 8 converts ordinary for-loops into the functional notation by hitting the ALT+ENTER key on, or by clicking on the yellow bulb. See you at Java EE Workshops at MUC Airport or on demand and in a location very near you: airhacks.io!

Java 8 forEach examples, 2.2 In Java 8, you can loop a List with forEach + lambda expression or method reference. List<String> items = new ArrayList<>(); items.add("A");  - Java 8 forEach examples. In this article, we will show you how to loop a List and a Map with the new Java 8 forEach statement.. 1. forEach and Map. 1.1 Normal way to loop a Map.

Comments
  • Those are lambdas you're working with, that's what you should be looking for, you pretty much got the for each right.
  • Should be using groupingBy ideally.
  • You can also use obj -> Collections.singletonMap(obj.getId(), obj.getFieldType()) as value mapper function.
  • +1, I would add that it is not required to explicitly mark them as final, just that they be effectively final, which means the lambda cannot assign a new value to the variable.
  • Yes that's fine now
  • list.forEach != list.stream().forEach, nothing bad in mutating using the first, which is what the OP does.