11/04/2014
3:54:00 PM 0

Java flatMap vs C# SelectMany

  • Old Java
    String[][] names = { { "John", "Mary", "Steven" }, { "Tom", "Jeff" } };
    List<String> list1 = new ArrayList<String>();  
    for (String[] s1 : names) {
        for (String s2 : s1) {
            list1.add(s2);
        }
    }
    
  • Java 8 Stream API
    String[][] names = { { "John", "Mary", "Steven" }, { "Tom", "Jeff" } };
    List<String> list2 = Arrays.stream(names)
        .flatMap(s1 -> Arrays.stream(s1))
        .collect(Collectors.toList());
    
  • C# LINQ (method syntax)
    string[][] names = { new string[] { "John", "Mary", "Steven" }, new string[] { "Tom", "Jeff" } };
    List<string> list3 = names.SelectMany(s1 => s1).ToList();
    

0 comments:

Post a Comment