Java string array with key

Java Array arrayContainsStartsWith(String[] array, String key)

Determines if the array contains a string that starts with the key. Case insensitive.

true if the array contains the key, false otherwise.

//package com.java2s; public class Main < /**// w w w . d e m o 2 s . c o m * Determines if the array contains a string that starts with the key. Case * insensitive. * * @param array the string array. * @param key the string to find. * @return true if the array contains the key, false otherwise. */ public static boolean arrayContainsStartsWith(String[] array, String key) < String upperKey = key.toUpperCase(); if (array == null) < return false; > for (String s : array) < if (s.toUpperCase().startsWith(upperKey)) < return true; > > return false; > >

  • Java Array arrayContainsItem(String[] items, String item)
  • Java Array arrayContainsLoose(String[] array, String value)
  • Java Array arrayContainsOnlyIgnoreCase(String[] array, String. strs)
  • Java Array arrayContainsStartsWith(String[] array, String key)
  • Java Array arrayContainsString(final String[] array, final String string)
  • Java Array arrayContainsString(String[] arr, String str, boolean isCaseSensitive)
  • Java Array arrayContainsString(String[] array, String string)

demo2s.com | Email: | Demo Source and Support. All rights reserved.

Источник

Associative Array in Java

associative array in java

An associative array stores the set of elements in the form of (key, value ) pairs. An associative array comprises unique keys and collections of values, associating each key with a single value. The associative array data structure in java benefits a wide range of applications. Like Perl and PHP (using hash variables), other programming languages implement the functionality to work with the associative array data structures. As the associative array stores elements in the form of (key, value) pair, to access the element from the associative array, we need to call the name of an array and passkey(whose value we want to access).

For example, an array(name as marks) stores students’ roll no and marks. To access the mark of a particular student, we should call this marks[102], where marks are an array name, and 102 is a rollno of a student, not an index number, which is not possible in an array of java. Therefore associative array technically not support in java, but it can be achieved using in the form of instances of the java.util.HashMap class.

Map map = new HashMap ( ); // creates Map where keys and values of string type //method to store elements map.put( "key1", "value1" ); map.put( "key2", "value2" ); // etc // method to access value map.get( "key1" ); // returns "value1" as output

How to Create an Associative Array in Java?

  • Java provides a Map class, or HashMap, which can be used as a type of array. The map Instead of referencing indexing (for example, 1, 2, 3, 4, 5, and so on), reference the objects of the array or reference the keys. So the map can be used as an alternative to the associative array.
  • You can use the put method to add an element to the array in a map. To access an element, the get method can be utilized. If you want to access all values of the array, the keySet function can be used. Also, we can remove elements from the map with the remove function and get the size of the array; the size method can be used (as the length function in arrays uses). So in simple words, a map associates (links) a value with a key.

Advantages of Associative Array

With the associative array, we can assign the meaningful key to values for array elements, save more elements, and assign the string as a key to an array’s elements.

Examples to Implement Associative Array in Java

We understand the above methods with the below sample java code. To create the map, we need to import the utilities that allow the use of the map. So we will import the Map and HashMap utilities. Below are examples of implementing an Associative Array in Java:

Example #1

Traverse Associative Array various methods

import java.util.HashMap; public class Demo < public static void main(String[] args ) < HashMap capitals = new HashMap (); capitals.put("Spain", "Madrid"); capitals.put("United Kingdom", "London"); capitals.put("India", "Delhi"); capitals.put("Argentina", "Buenos Aires"); System.out.println("The Size of capitals Map is : " + capitals.size()); // Remove an element from the HashMap capitals.remove("United Kingdom"); // To display size of the hashtmap System.out.println("The Size of capitals Map is : " + capitals.size()); // Check the existence of key in the Hashmap String key = "India"; if (capitals.containsKey( key )) < System.out.println("The capital of " + key + " is: " + capitals.get( key )); >else < System.out.println("There is no entry for the capital of " + key); >> >

Associative Array in Java - 1

Example #2

Traverse Associative Array using iterator methods

import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class DurationClassDemo < public static void main(String[] args) < HashMapcapitals = new HashMap(); capitals.put("Spain", "Madrid"); capitals.put("United Kingdom", "London"); capitals.put("India", "Delhi"); capitals.put("Argentina", "Buenos Aires"); System.out.println("The Size of capitals Map is : " + capitals.size()); Iterator i = capitals.entrySet().iterator(); // Iterate through the hashmap while (i.hasNext()) < Map.Entry ele = (Map.Entry)i.next(); System.out.println(ele.getKey() + " : " + ele.getValue()); >> >

Associative Array in Java - 2

Example #3

Traverse Associative Array using a for-each loop

import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class DurationClassDemo < public static void main(String[] args) < HashMapcapitals = new HashMap(); capitals.put("Spain", "Madrid"); capitals.put("United Kingdom", "London"); capitals.put("India", "Delhi"); capitals.put("Argentina", "Buenos Aires"); System.out.println("The Size of capitals Map is : " + capitals.size()); for (Map.Entry ele : capitals.entrySet()) < String key = (String)ele.getKey(); System.out.println(key + " : " + ele.getValue()); >> >

for-each loop

Example #4

Traverse Associative Array using the forEach( ) method of hashmap

import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class DurationClassDemo < public static void main(String[] args) < HashMapcapitals = new HashMap(); capitals.put("Spain", "Madrid"); capitals.put("United Kingdom", "London"); capitals.put("India", "Delhi"); capitals.put("Argentina", "Buenos Aires"); System.out.println("The Size of capitals Map is : " + capitals.size()); capitals.forEach((k, v) -> System.out.println(k + " : " + v )); > >

Traverse Associative

Conclusion

In simple words, an associative array in java stores the set of elements in a key; the value pair form an associative array is a collection of unique keys and collections of values where each key is associated with one value. We can use the hashMap built-in java class to achieve an associative array, as we have seen above examples.

This is a guide to Associative Array in Java. Here we discuss Syntax, how to create an associative array in java, and examples and advantages. You can also go through our other related articles to learn more –

89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8

Источник

Associative Array in Java

Associative Array in Java

  1. Use the Associative Array in Java
  2. Abstract of the Associative Array in Java
  3. Implement an Associative Array in Java
  4. Create an Associative Array in Java
  5. Add Elements to the Associative Array in Java
  6. Traverse Elements of the Associative Array in Java
  7. Traverse Elements of the Associative Array Using forEach() Method in Java 8

An associative array is a type of array that stores the set of elements in key and value pairs. It is a collection of keys and values where the key is unique and is associated with one value.

If we have to access the element from the associative array, we must call the array’s name and pass the key whose value we want to access .

Use the Associative Array in Java

For example, we have an array named marks that stores the roll number and students’ marks.

So if we have to access the mark of a particular student, then we can call like this marks 105 , where marks are the name of an array and 105 is the roll number of the student, not an index number which is not possible in an array if we are using Java language.

Therefore associative array does not support Java, but we can easily achieve it using HashMap . Java does not support associative array but can be implemented using the Map.

Abstract of the Associative Array in Java

HashMapString, String> hashmap = new HashMap<>();  // method to add the key,value pair in hashmap  hashmap.put("Key1", "Value1");  hashmap.put("Key2", "Value2");  hashmap.put("Key3", "Value3");  // and many more.  // get the value 1 and 2  System.out.println(hashmap.get("Key1"));  System.out.println(hashmap.get("Key2"));  // and many more. 

Implement an Associative Array in Java

To implement an associative array in Java, we used HashMap , an implementation class of Map interface. Let’s understand step by step.

First, import and initialize the HashMap , i.e., create an instance of HashMap by using the following statements.

import java.util.HashMap; HashMapString, String> hashmap = new HashMap<>(); 

Then, using the put() method, add the key value to the HashMap .

Convert the HashMap to Set using the entrySet() method to remove duplicate keys.

SetMap.EntryString ,String> > set = map.entrySet(); 

Convert the Set to an ArrayList which is an array that we want.

ListMap.EntryString ,String>> list=new ArrayList<>(set); 

Create an Associative Array in Java

In this example, we used the HashMap class to implement the associative array in Java.

See, it contains data in key-value pair format, and we used the getKey() method to access the key and the getValue() method to access values.

import java.io.*; import java.util.*; public class SimpleTesting   public static void main(String[] args)   HashMapString, String> hashmap = new HashMap<>();  hashmap.put("Virat", "Batsman");  hashmap.put("Bumrah", "Bowler");  hashmap.put("Jadeja", "All-rounder");  hashmap.put("Pant", "Wicket-Keeper");   SetMap.EntryString, String>> s = hashmap.entrySet();  ListMap.EntryString, String>> array = new ArrayList<>(s);  for (int i = 0; i  array.size(); i++)   System.out.println(array.get(i).getKey() + " is " + array.get(i).getValue());  >  > > 
Pant is Wicket-Keeper Jadeja is All-rounder Bumrah is Bowler Virat is Batsman 

As we have already discussed, that key should be unique. If we insert the same keys in the associative array, it will discard one of the key-value pairs.

We have inserted two same keys, Virat , in the following code. See the example below.

import java.io.*; import java.util.*; public class SimpleTesting   public static void main(String[] args)   HashMapString, String> hashmap = new HashMap<>();  hashmap.put("Virat", "Batsman");  hashmap.put("Bumrah", "Bowler");  hashmap.put("Jadeja", "All-rounder");  hashmap.put("Pant", "Wicket-Keeper");  hashmap.put("Virat", "Captain");   SetMap.EntryString, String>> s = hashmap.entrySet();  ListMap.EntryString, String>> array = new ArrayList<>(s);  for (int i = 0; i  array.size(); i++)   System.out.println(array.get(i).getKey() + " is " + array.get(i).getValue());  >  > > 
Pant is Wicket-Keeper Jadeja is All-rounder Bumrah is Bowler Virat is Captain 

Add Elements to the Associative Array in Java

We can add an element to an array in the map by using the put() method. Similarly, we can remove an element from an array using the remove() method.

We can find out the size of the array by using the size() method.

import java.util.HashMap; public class SimpleTesting   public static void main(String[] args)   HashMapString, String> fruits = new HashMapString, String>();  fruits.put("Apple", "Red");  fruits.put("Banana", "Yellow");  fruits.put("Guava", "Green");  fruits.put("Blackberries", "Purple");   System.out.println("The Size of fruits Map is : " + fruits.size());  // Remove Banana from the HashMap  fruits.remove("Banana");  // To find out the size of the Hashmap  System.out.println("The Size of fruits Map is : " + fruits.size());  // Check whether the key is present in the Hashmap or not  String fruit_key = "Apple";  if (fruits.containsKey(fruit_key))   System.out.println("The colour of " + fruit_key + " is: " + fruits.get(fruit_key));  > else   System.out.println("There is no entry for the fruit of " + fruit_key);  >  > > 
The Size of fruits Map is : 4 The Size of fruits Map is : 3 The colour of Apple is: Red 

Traverse Elements of the Associative Array in Java

We can use the for-each loop to traverse the associative array. Since HashMap belongs to the java.util package, we can use the foreach loop to iterate its elements.

import java.util.HashMap; import java.util.Iterator; import java.util.Map;  public class SimpleTesting   public static void main(String[] args)    HashMapString, String> fruits = new HashMapString, String>();  fruits.put("Apple", "Red");  fruits.put("Banana", "Yellow");  fruits.put("Guava", "Green");  fruits.put("Blackberries", "Purple");  System.out.println("The Size of fruits Map is : " + fruits.size());  for (Map.Entry element : fruits.entrySet())   String key = (String) element.getKey();  System.out.println(key + " : " + element.getValue());  >  > > 
The Size of fruits Map is : 4 Guava : Green Apple : Red Blackberries : Purple Banana : Yellow 

Traverse Elements of the Associative Array Using forEach() Method in Java 8

If you are working with Java 8 or a higher version, you can use the forEach() method to traverse the array elements. The forEach() method requires a lambda expression as an argument.

import java.util.HashMap; import java.util.Iterator; import java.util.Map;  public class SimpleTesting   public static void main(String[] args)   HashMapString, String> fruits = new HashMapString, String>();  fruits.put("Apple", "Red");  fruits.put("Banana", "Yellow");  fruits.put("Guava", "Green");  fruits.put("Blackberries", "Purple");   System.out.println("The Size of fruits Map is : " + fruits.size());  fruits.forEach((k, v) -> System.out.println(k + " : " + v));  > > 
The Size of fruits Map is : 4 Guava : Green Apple : Red Blackberries : Purple Banana : Yellow 

This tutorial studied that Java technically does not support the associative array, but we can easily achieve it using HashMap .

Related Article — Java Array

Copyright © 2023. All right reserved

Источник

Читайте также:  Add custom php to wordpress
Оцените статью