Java args to map

Java 8 Stream map() Example

On this page we will provide java 8 Stream map() example. It returns a Stream instance processed by a given Function. map() returns the stream of objects and to get the stream of primitive data type such as IntStream , LongStream and DoubleStream , java 8 Stream provides the method as mapToInt() , mapToLong() and mapToDouble() respectively.

Contents

Stream map() with Function

The syntax of Stream.map() method is as follows.

We need to pass Function instance as lambda expression. This method returns Stream instance that has the result processed by given Function . This is an intermediate operation.

Convert Map to List using Stream map()

Here we will convert a HashMap into a List of objects using Stream.map() as an intermediate operation.
MapToList.java

package com.concretepage; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class MapToList < public static void main(String[] args) < Map&ltInteger, String&gt map = new HashMap&lt&gt(); map.put(111, "Lalkrishna"); map.put(154, "Atal"); map.put(30, "Narendra"); map.put(200, "Amit"); List&ltUser&gt list = map.entrySet().stream().sorted(Comparator.comparing(e -&gt e.getKey())) .map(e -&gt new User(e.getKey(), e.getValue())).collect(Collectors.toList()); list.forEach(l -&gt System.out.println("Id: "+ l.getId()+", Name: "+ l.getName())); >> class User < private int id; private String name; public User(int id, String name) < this.id = id; this.name = name; >public int getId() < return id; >public String getName() < return name; >>
Id: 30, Name: Narendra Id: 111, Name: Lalkrishna Id: 154, Name: Atal Id: 200, Name: Amit

Convert List to another List using Stream map()

In this example we will convert a List of an object into another List of different object using Stream.map() as an intermediate operation.
ListToAnotherList.java

package com.concretepage; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ListToAnotherList < public static void main(String[] args) < Person p1 = new Person(1, "Mohan", "student"); Person p2 = new Person(2, "Sohan", "teacher"); Person p3 = new Person(3, "Dinesh", "student"); List&ltPerson&gt personList = Arrays.asList(p1, p2, p3); List&ltStudent&gt stdList = personList.stream().filter(p -&gt p.getPersonType().equals("student")) .map(p -&gt new Student(p.getId(), p.getName())) .collect(Collectors.toList()); stdList.forEach(e -&gt System.out.println("Id:"+ e.getId()+ ", Name: "+ e.getName())); >> class Person < private int id; private String name; private String personType; public Person(int id, String name, String personType) < this.id = id; this.name = name; this.personType = personType; >public int getId() < return id; >public String getName() < return name; >public String getPersonType() < return personType; >> class Student < private int id; private String name; public Student(int id, String name) < this.id = id; this.name = name; >public int getId() < return id; >public String getName() < return name; >>
Id:1, Name: Mohan Id:3, Name: Dinesh

Stream mapToInt() Example

Here we are providing the example of mapToInt() and in the same way we can do for mapToLong() and mapToDouble() .
MapToIntDemo.java

package com.concretepage; import java.util.Arrays; import java.util.List; public class MapToIntDemo < public static void main(String[] args) < Employee e1 = new Employee(1, 20); Employee e2 = new Employee(2, 15); Employee e3 = new Employee(3, 30); List&ltEmployee&gt list = Arrays.asList(e1, e2, e3); int sum = list.stream().mapToInt(e -&gt e.getAge()).sum(); System.out.println("Sum: "+ sum); >> class Employee < private int id; private int age; public Employee(int id, int age) < this.id = id; this.age = age; >public int getId() < return id; >public int getAge() < return age; >>

Источник

Читайте также:  Java прочитать файл построчно

Command Line Arguments in Java — Accessing and Mapping to Data Types

Command line arguments (parameters) are strings of text used to pass additional information to a program when an application is run through the command line interface (CLI) of an operating system.

In this tutorial, we’ll be accessing the arguments (parameters) passed into the main method of a Java application and reading them. We’ll also map them to different data types so that we can handle them and alter the flow of the code based on the input.

Accessing Command Line Arguments

The entry-point for every Java program is the main() method:

public static void main(String[] args) < // Do something > 

The arguments passed to the program as it was initialized are stored in the args array. Alternatively, Java also supports a vararg in this place:

public static void main(String. args) < // Do something > 

That being said, we can easily access each argument passed into this method. Let’s start out by printing them out, one by one:

public class Main < public static void main(String[] args) < for (int i = 0; i < args.length; i++) System.out.println(String.format("Argument %d: %s", i, args[i])); > > 

We’ll then compile this .java file:

After which, we can run it:

Argument 0: Hello Argument 1: World 

Mapping Arguments to Data Types

The arguments themselves are an array of Strings. So really, everything we pass is a String. Though, we can convert Strings into different data types as well:

Argument 0: Hello Argument 1: 15 Argument 2: true 

Say we wanted to allow the users to print a String a set number of times, and have a flag that toggles a log message that displays the number of the iteration. The arguments provided above would thus print Hello 15 times, with a log message on each print() statement.

public class Main < public static void main(String[] args) < String s = ""; int n = 0; boolean flag = false; try < s = args[0]; > catch (Exception e) < System.out.println("The first argument must be present."); System.exit(1); > try < n = Integer.parseInt(args[1]); > catch (NumberFormatException e) < System.out.println("The second argument must be an integer."); System.exit(1); > try < flag = Boolean.parseBoolean(args[2]); > catch (Exception e) < System.out.println("The third argument must be parseable to boolean."); System.exit(1); > for (int i = 0; i < n; i++) < System.out.println(s); if (flag) System.out.println(String.format("Iteration %d", i)); > > > 

Now, let’s compile the code again:

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

And then, let’s run it with no arguments:

The first argument must be present. 

If we provide the arguments:

Hello Iteration 0 Hello Iteration 1 Hello Iteration 2 Hello Iteration 3 Hello Iteration 4 

Setting Arguments in IDEs

This assumes that you run the code through the command line, which isn’t always the case. Most people use IDEs to work on their projects, which have a convenient «Run» button instead.

Читайте также:  Установка webdriver для python

Thankfully, you can tell the IDE to pass these arguments into the run call. Here are examples of how you can do that with some popular IDEs:

Источник

Convert Stream Element to Map in Java

Convert Stream Element to Map in Java

  1. Stream of Strings to Map in Java
  2. Create Map From the Objects of Stream in Java
  3. Determine Values Length While Converting Stream to Map in Java
  4. Convert Stream to Map for Unique Product Keys in Java

We will go over the practical uses of Java Streams and how to convert stream elements into map elements.

To understand this article, you must have a basic understanding of Java 8, particularly lambda expressions and the Stream API. But, if you are a newbie, do not worry; we will explain everything.

Stream of Strings to Map in Java

  1. Collectors.toMap() — It performs different functional reduction operations, such as collecting elements into collections.
  2. toMap — It returns a Collector that gathers elements into a Map with keys and values.
MapString, String> GMS =  stream.collect(Collectors.toMap(k->k[0],k-> k[1])); 

Got it? We will specify appropriate mapping functions to define how to retrieve keys and values from stream elements.

Implementation of Example1.java :

package delftstackStreamToMapJava; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream;  public class Example1   // Method to get stream of `String[]`  private static StreamString[]> MapStringsStream()    return Stream.of(new String[][]   "Sky", "Earth">,  "Fire", "Water">,  "White", "Black">,  "Ocean", "Deep">,  "Life", "Death">,  "Love", "Fear">  >);  >  // Program to convert the stream to a map in Java 8 and above  public static void main(String[] args)    // get a stream of `String[]`  StreamString[]> stream = MapStringsStream();   // construct a new map from the stream  MapString, String> GMS =  stream.collect(Collectors.toMap(k->k[0],k-> k[1]));   System.out.println(GMS);  > > 

Create Map From the Objects of Stream in Java

This program is another simple demonstration of using the Collectors.toMap() method.

Besides, it also uses references function/lambda expression. So, we recommend you check it for a few minutes.

Check out our three streams:

ListDouble> L1 = Arrays.asList(1.1,2.3); ListString> L2 = Arrays.asList("A","B","C"); ListInteger> L3 = Arrays.asList(10,20,30); 

To add more to our primary mapping method:
2.1 It takes a key and value mapper to generate a Map from Stream objects.
2.2 Stream , in this case, is our array lists, which are then passed to Collectors for reduction while getting mapped in keys with the help of .toMap .

MapDouble, Object> printL1 = L1.stream()  .collect(Collectors.toMap(Function.identity(), String::valueOf, (k1, k2) -> k1));  System.out.println("Stream of Double to Map: " + printL1); 

Implementation of Example2.java :

package delftstackStreamToMapJava;  import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors;  public class Example2   public static void main(String[] args)   // Stream of Integers  ListDouble> L1 = Arrays.asList(1.1, 2.3);  ListString> L2 = Arrays.asList("A", "B", "C");  ListInteger> L3 = Arrays.asList(10, 20, 30);  MapDouble, Object> printL1 = L1.stream()  .collect(Collectors.toMap(Function.identity(), String::valueOf, (k1, k2) -> k1));  System.out.println("Stream of Double to Map: " + printL1);   MapString, Object> printL2 = L2.stream()  .collect(Collectors.toMap(Function.identity(), String::valueOf, (k1, k2) -> k1));  System.out.println("Stream of String to Map: " + printL2);   MapInteger, Object> printL3 = L3.stream()  .collect(Collectors.toMap(Function.identity(), String::valueOf, (k1, k2) -> k1));  System.out.println("Stream of Integers to Map: " + printL3);   > > 
Stream of Double to Map: Stream of String to Map: Stream of Integers to Map: 

Determine Values Length While Converting Stream to Map in Java

The following code block converts a string into a Map , with the keys representing the string value and the value indicating the length of each word. This is our final example, although this one falls into the category of an elementary stream to map elementary examples.

  1. stream-> stream — determines the Stream value and returns it as the map’s key.
  2. stream-> stream.length — finds the present stream value, finds its length and returns it to the map for the given key.

Implementation of Example3.java :

package delftstackStreamToMapJava;  import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors;  public class Example3   public static MapString, Integer> toMap(String str)   MapString, Integer> elementL = Arrays.stream(str.split("/"))  .collect(Collectors.toMap(stream -> stream, stream -> stream.length()));   return elementL;  >   public static void main(String[] args)   String stream = "We/Will/Convert/Stream/Elements/To/Map";   System.out.println(toMap(stream));  > > 

Convert Stream to Map for Unique Product Keys in Java

We will convert a stream of integer pro_id and string’s productname . Not to get confused, though!

This is yet another implementation of a collection of streams to map values.

It is sequential, and the keys here are unique pro_id . The whole program is the same as an example two except for its concept.

This is the somewhat more realistic situation of using streams to map. It will also enable your understanding of how many ways you can construct a customized program that extracts unique values and keys from array objects.

Implementation of Products.java :

package delftstackStreamToMapJava;  import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors;  public class Products   private Integer pro_id;  private String productname;   public Products(Integer pro_id, String productname)   this.pro_id = pro_id;  this.productname = productname;  >   public Integer extractpro_id()   return pro_id;  >   public String getproductname()   return productname;  >   public String toString()   return "[productid = " + this.extractpro_id() + ", productname = " + this.getproductname() + "]";  >   public static void main(String args[])    ListProducts> listofproducts = Arrays.asList(new Products(1, "Lamda 2.0 "), new Products(2, "Gerrio 3A ultra"),  new Products(3, "Maxia Pro"), new Products(4, "Lemna A32"), new Products(5, "Xoxo Pro"));   MapInteger, Products> map = listofproducts.stream()  .collect(Collectors.toMap(Products::extractpro_id, Function.identity()));  map.forEach((key, value) ->   System.out.println(value);  >);   > > 
[productid = 1, productname = Lamda 2.0 ] [productid = 2, productname = Gerrio 3A ultra] [productid = 3, productname = Maxia Pro] [productid = 4, productname = Lemna A32] [productid = 5, productname = Xoxo Pro] 

Источник

Оцените статью