Как изменить значение массива на другое

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

array_replaceЗаменяет элементы массива элементами других переданных массивов

Описание

array_replace(array $array, array ...$replacements): array

array_replace() не рекурсивная: значения первого массива
будут заменены вне зависимости от типа значений второго массива, даже если
это будут вложенные массивы.

Список параметров

array

Массив, элементы которого требуется заменить.

replacements

Массивы, из которых будут браться элементы для замены.
Значения следующего массива затирают значения предыдущего.

Возвращаемые значения

Возвращает массив (array).

Примеры

Пример #1 Пример использования array_replace()


<?php
$base
= array("orange", "banana", "apple", "raspberry");
$replacements = array(0 => "pineapple", 4 => "cherry");
$replacements2 = array(0 => "grape");$basket = array_replace($base, $replacements, $replacements2);
print_r($basket);
?>

Результат выполнения данного примера:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

Смотрите также

  • array_replace_recursive() — Рекурсивно заменяет элементы первого массива элементами переданных массивов
  • array_merge() — Сливает один или большее количество массивов

steelpandrummer

10 years ago


<?php
// we wanted the output of only selected array_keys from a big array from a csv-table
// with different order of keys, with optional suppressing of empty or unused values
$values = array
(
   
'Article'=>'24497',
   
'Type'=>'LED',
   
'Socket'=>'E27',
   
'Dimmable'=>'',
   
'Wattage'=>'10W'
);$keys = array_fill_keys(array('Article','Wattage','Dimmable','Type','Foobar'), ''); // wanted array with empty value$allkeys = array_replace($keys, array_intersect_key($values, $keys));    // replace only the wanted keys$notempty = array_filter($allkeys, 'strlen'); // strlen used as the callback-function with 0==falseprint '<pre>';
print_r($allkeys);
print_r($notempty);/*
Array
(
    [Article] => 24497
    [Wattage] => 10W
    [Dimmable] =>
    [Type] => LED
    [Foobar] =>
)
Array
(
    [Article] => 24497
    [Wattage] => 10W
    [Type] => LED
)
*/
?>

marvin_elia at web dot de

8 years ago


Simple function to replace array keys. Note you have to manually select wether existing keys will be overrided.

/**
  * @param array $array
  * @param array $replacements
  * @param boolean $override
  * @return array
  */
function array_replace_keys(array $array, array $replacements, $override = false) {
    foreach ($replacements as $old => $new) {
        if(is_int($new) || is_string($new)){
            if(array_key_exists($old, $array)){
                if(array_key_exists($new, $array) && $override === false){
                    continue;
                }
                $array[$new] = $array[$old];
                unset($array[$old]);
            }
        }
    }
    return $array;
}


ali dot sweden19 at yahoo dot com

7 years ago


Here is a simple array_replace_keys function:

/**
     * This function replaces the keys of an associate array by those supplied in the keys array
     *
     * @param $array target associative array in which the keys are intended to be replaced
     * @param $keys associate array where search key => replace by key, for replacing respective keys
     * @return  array with replaced keys
     */
    private function array_replace_keys($array, $keys)
    {
        foreach ($keys as $search => $replace) {
            if ( isset($array[$search])) {
                $array[$replace] = $array[$search];
                unset($array[$search]);
            }
        }

        return $array;
    }

// Test Drive

print_r(array_replace_keys(['one'=>'apple', 'two'=>'orange'], ['one'=>'ett', 'two'=>'tvo']);
// Output
array(
'ett'=>'apple',
'tvo'=>'orange'
)


mail at romansklenar dot cz

13 years ago


To get exactly same result like in PHP 5.3, the foreach loop in your code should look like:

<?php

...

$count = func_num_args();

for (

$i = 1; $i < $count; $i++) {

   ...

}

...

?>



Check on this code:

<?php

$base
= array('id' => NULL, 'login' => NULL, 'credit' => NULL);

$arr1 = array('id' => 2, 'login' => NULL, 'credit' => 5);

$arr2 = array('id' => NULL, 'login' => 'john.doe', 'credit' => 100);

$result = array_replace($base, $arr1, $arr2);
/*

correct output:

array(3) {

   "id" => NULL

   "login" => string(8) "john.doe"

   "credit" => int(100)

}

your output:

array(3) {

   "id" => int(2)

   "login" => NULL

   "credit" => int(5)

}

*/

?>



Function array_replace "replaces elements from passed arrays into the first array" -- this means replace from top-right to first, then from top-right - 1 to first, etc, etc...


gmastro77 at gmail dot com

9 years ago


In some cases you might have a structured array from the database and one
of its nodes goes like this;

<?php
# a random node structure
$arr    = array(
   
'name'  => 'some name',
   
'key2'  => 'value2',
   
'title' => 'some title',
   
'key4'  => 4,
   
'json'  => '[1,0,1,1,0]'
);# capture these keys values into given order
$keys   = array( 'name', 'json', 'title' );
?>

Now consider that you want to capture $arr values from $keys.
Assuming that you have a limitation to display the content into given keys
order, i.e. use it with a vsprintf, you could use the following

<?php
# string to transform
$string = "<p>name: %s, json: %s, title: %s</p>";# flip keys once, we will use this twice
$keys   = array_flip( $keys );# get values from $arr
$test   = array_intersect_key( $arr, $keys );# still not good enough
echo vsprintf( $string, $test );
// output --> name: some name, json: some title, title: [1,0,1,1,0]

# usage of array_replace to get exact order and save the day

$test   = array_replace( $keys, $test );# exact output
echo vsprintf( $string, $test );
// output --> name: some name, json: [1,0,1,1,0], title: some title?>

I hope that this will save someone's time.


polecat at p0lecat dot com

12 years ago


I got hit with a noob mistake. :)

When the function was called more than once, it threw a function redeclare error of course.  The enviroment I was coding in never called it more than once but I caught it in testing and here is the fully working revision.  A simple logical step was all that was needed.

With PHP 5.3 still unstable for Debian Lenny at this time and not knowing if array_replace would work with multi-dimensional arrays, I wrote my own.  Since this site has helped me so much, I felt the need to return the favor. :)

<?php

       
// Polecat's Multi-dimensional array_replace function

        // Will take all data in second array and apply to first array leaving any non-corresponding values untouched and intact

       
function polecat_array_replace( array &$array1, array &$array2 ) {

           
// This sub function is the iterator that will loop back on itself ad infinitum till it runs out of array dimensions

           
if(!function_exists('tier_parse')){

                function
tier_parse(array &$t_array1, array&$t_array2) {

                    foreach (
$t_array2 as $k2 => $v2) {

                        if (
is_array($t_array2[$k2])) {

                           
tier_parse($t_array1[$k2], $t_array2[$k2]);

                        } else {

                           
$t_array1[$k2] = $t_array2[$k2];

                        }

                    }

                    return
$t_array1;

                }

            }

           
            foreach (

$array2 as $key => $val) {

                if (
is_array($array2[$key])) {

                   
tier_parse($array1[$key], $array2[$key]);

                } else {

                   
$array1[$key] = $array2[$key];

                }

            }

            return
$array1;

        }

?>



[I would also like to note] that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

<?php

$array1
= array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );
$array2 = array( "food" => "wine");
$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);

?>



This is will replace the value for "food" for "dewberry" with "wine".

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I've gained from this site.


kyberprizrak

8 years ago


if(!function_exists('array_replace'))
{
  function array_replace()
  {
    $args = func_get_args();
    $num_args = func_num_args();
    $res = array();
    for($i=0; $i<$num_args; $i++)
    {
      if(is_array($args[$i]))
      {
        foreach($args[$i] as $key => $val)
        {
          $res[$key] = $val;
        }
      }
      else
      {
        trigger_error(__FUNCTION__ .'(): Argument #'.($i+1).' is not an array', E_USER_WARNING);
        return NULL;
      }
    }
    return $res;
  }
}

sun at drupal dot org

11 years ago


Instead of calling this function, it's often faster and simpler to do this instead:

<?php
$array_replaced
= $array2 + $array1;
?>

If you need references to stay intact:

<?php
$array2
+= $array1;
?>


lm713

8 years ago


If the arrays are associative (that is, their keys are strings), then I believe this function is identical to (the older) array_merge.

ricardophp yahoocombr

10 months ago


Concerning the affirmation:
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator

Clearing the fact (it means ...):
If the first array have a key and a value it will not be overlap by the new array. therefore if you have an array like [1=>"alpha", 2=>"beta"] and you got a new array telling [1=>"Alpha", 3=>"Gamma"] the final array will be [1=>"alpha", 2=>"beta", 3=>"Gamma"]. The values of first array will not be modified in the result array.

So, if you are building a concatenation array where the values sometimes overlaps each other keys and you must preserve values you better use array_merge instead "plus" sign


projacore at gmail dot com

7 years ago


You can also use:

<?php
$myarray
= [
"Orange",
"572" => "Banana",
"omg" => "Chili",
"nevermind" => "mango"
];$myarray[0] = "NO-Orange";
$myarray["572"] = "BANANAPHONE!!!";
$myarray["omg"] = "NO-Chili";print_r($myarray);?>

RESULT:
Array
(
    [0] => NO-Orange
    [572] => BANANAPHONE!!!
    [omg] => NO-Chili
    [nevermind] => mango
)

with regards


polecat at p0lecat dot com

12 years ago


I would like to add to my previous note about my polecat_array_replace function that if you want to add a single dimensional array to a multi, all you must do is pass the matching internal array key from the multi as the initial argument as such:

$array1 = array( "berries" => array( "strawberry" => array( "color" => "red", "food" => "desserts"), "dewberry" = array( "color" => "dark violet", "food" => "pies"), );

$array2 = array( "food" => "wine");

$array1["berries"]["dewberry"] = polecat_array_replace($array1["berries"]["dewberry"], $array2);

This is will replace the value for "food" for "dewberry" with "wine".

The function will also do the reverse and add a multi to a single dimensional array or even a 2 tier array to a 5 tier as long as the heirarchy tree is identical.

I hope this helps atleast one person for all that I've gained from this site.


Anonymous

7 years ago


The documentation is wrongly phrased: "array_replace() replaces the values of array1"  No replacing is done. A new array is created which looks like the one that would have resulted from the described replacement.

If you want to augment the set of indices in an array, use
       array_to_be_modified += array_with_indices_to_add;


tufan dot oezduman at googlemail dot com

13 years ago


a little enhancement to dyer85 at gmail dot com's function below:
<?php
if (!function_exists('array_replace'))
{
  function
array_replace( array &$array, array &$array1, $filterEmpty=false )
  {
   
$args = func_get_args();
   
$count = func_num_args()-1;

    for (

$i = 0; $i < $count; ++$i) {
      if (
is_array($args[$i])) {
        foreach (
$args[$i] as $key => $val) {
            if (
$filterEmpty && empty($val)) continue;
           
$array[$key] = $val;
        }
      }
      else {
       
trigger_error(
         
__FUNCTION__ . '(): Argument #' . ($i+1) . ' is not an array',
         
E_USER_WARNING
       
);
        return
NULL;
      }
    }

    return

$array;
  }
}
?>

this will allow you to "tetris-like" merge arrays:

<?php

$a

= array(
   
0 => "foo",
   
1 => "",
   
2 => "baz"
);
$b= array(
   
0 => "",
   
1 => "bar",
   
2 => ""
);print_r(array_replace($a,$b, true));?>
results in:
Array
(
    [0] => foo
    [1] => bar
    [2] => baz
)


ivijan dot stefan at gmail dot com

6 years ago


If you work on some realy old server below PHP5 you can use array_merge like "necessary evil" to replace values in array:

Here is example how you can use this:

<?php
if(function_exists("array_replace") && version_compare(phpversion(), '5.3.0', '>='))
       
$data = array_replace($array1, $array2); // (PHP 5 >= 5.3.0)
   
else
       
$data = array_merge($array1, $array2); // (PHP 5 < 5.3.0)
var_dump($data);
?>

This can also help someplugin developers to cover some old PHP versions.


var index = items.indexOf(3452);

if (index !== -1) {
    items[index] = 1010;
}

Also it is recommend you not use the constructor method to initialize your arrays. Instead, use the literal syntax:

var items = [523, 3452, 334, 31, 5346];

You can also use the ~ operator if you are into terse JavaScript and want to shorten the -1 comparison:

var index = items.indexOf(3452);

if (~index) {
    items[index] = 1010;
}

Sometimes I even like to write a contains function to abstract this check and make it easier to understand what’s going on. What’s awesome is this works on arrays and strings both:

var contains = function (haystack, needle) {
    return !!~haystack.indexOf(needle);
};

// can be used like so now:
if (contains(items, 3452)) {
    // do something else...
}

Starting with ES6/ES2015 for strings, and proposed for ES2016 for arrays, you can more easily determine if a source contains another value:

if (haystack.includes(needle)) {
    // do your thing
}

answered May 6, 2011 at 18:56

Eli's user avatar

EliEli

17.1k4 gold badges36 silver badges49 bronze badges

3

The Array.indexOf() method will replace the first instance. To get every instance use Array.map():

a = a.map(function(item) { return item == 3452 ? 1010 : item; });

Of course, that creates a new array. If you want to do it in place, use Array.forEach():

a.forEach(function(item, i) { if (item == 3452) a[i] = 1010; });

answered May 6, 2011 at 19:03

gilly3's user avatar

gilly3gilly3

86.4k25 gold badges143 silver badges174 bronze badges

4

My suggested solution would be:

items.splice(1, 1, 1010);

The splice operation will start at index 1, remove 1 item in the array (i.e. 3452), and will replace it with the new item 1010.

DannyMoshe's user avatar

DannyMoshe

5,6803 gold badges29 silver badges49 bronze badges

answered Sep 29, 2018 at 7:38

Shimon Agassi's user avatar

1

Answer from @gilly3 is great.

Replace object in an array, keeping the array order unchanged

I prefer the following way to update the new updated record into my array of records when I get data from the server. It keeps the order intact and quite straight forward one liner.

users = users.map(u => u.id !== editedUser.id ? u : editedUser);

var users = [
{id: 1, firstname: 'John', lastname: 'Ken'},
{id: 2, firstname: 'Robin', lastname: 'Hood'},
{id: 3, firstname: 'William', lastname: 'Cook'}
];

var editedUser = {id: 2, firstname: 'Michael', lastname: 'Angelo'};

users = users.map(u => u.id !== editedUser.id ? u : editedUser);

console.log('users -> ', users);

answered Jun 5, 2020 at 10:44

muasif80's user avatar

muasif80muasif80

5,2763 gold badges31 silver badges45 bronze badges

3

Use indexOf to find an element.

var i = items.indexOf(3452);
items[i] = 1010;

BuZZ-dEE's user avatar

BuZZ-dEE

5,51410 gold badges65 silver badges94 bronze badges

answered May 6, 2011 at 18:55

Tesserex's user avatar

TesserexTesserex

17.1k5 gold badges65 silver badges105 bronze badges

1

First method

Best way in just one line to replace or update item of array

array.splice(array.indexOf(valueToReplace), 1, newValue)

Eg:

let items = ['JS', 'PHP', 'RUBY'];

let replacedItem = items.splice(items.indexOf('RUBY'), 1, 'PYTHON')

console.log(replacedItem) //['RUBY']
console.log(items) //['JS', 'PHP', 'PYTHON']

Second method

An other simple way to do the same operation is :

items[items.indexOf(oldValue)] = newValue

answered Feb 8, 2020 at 22:31

Goms's user avatar

GomsGoms

2,3444 gold badges19 silver badges36 bronze badges

1

Easily accomplished with a for loop.

for (var i = 0; i < items.length; i++)
    if (items[i] == 3452)
        items[i] = 1010;

answered May 6, 2011 at 18:55

mellamokb's user avatar

mellamokbmellamokb

55.8k12 gold badges108 silver badges136 bronze badges

1

If using a complex object (or even a simple one) and you can use es6, Array.prototype.findIndex is a good one. For the OP’s array, they could do,

const index = items.findIndex(x => x === 3452)
items[index] = 1010

For more complex objects, this really shines. For example,

const index = 
    items.findIndex(
       x => x.jerseyNumber === 9 && x.school === 'Ohio State'
    )

items[index].lastName = 'Utah'
items[index].firstName = 'Johnny'

answered Dec 28, 2018 at 0:14

Yatrix's user avatar

YatrixYatrix

13.1k15 gold badges46 silver badges78 bronze badges

1

You can edit any number of the list using indexes

for example :

items[0] = 5;
items[5] = 100;

Vamshi's user avatar

Vamshi

9,1044 gold badges37 silver badges54 bronze badges

answered May 6, 2011 at 18:56

VirtualTroll's user avatar

VirtualTrollVirtualTroll

3,0171 gold badge28 silver badges46 bronze badges

0

ES6 way:

const items = Array(523, 3452, 334, 31, ...5346);

We wanna replace 3452 with 1010, solution:

const newItems = items.map(item => item === 3452 ? 1010 : item);

Surely, the question is for many years ago and for now I just prefer to use immutable solution, definitely, it is awesome for ReactJS.

For frequent usage I offer below function:

const itemReplacer = (array, oldItem, newItem) =>
  array.map(item => item === oldItem ? newItem : item);

answered Feb 22, 2020 at 20:22

AmerllicA's user avatar

AmerllicAAmerllicA

26.7k14 gold badges125 silver badges148 bronze badges

A functional approach to replacing an element of an array in javascript:

const replace = (array, index, ...items) => [...array.slice(0, index), ...items, ...array.slice(index + 1)];

answered Nov 28, 2020 at 3:26

bmaggi's user avatar

bmaggibmaggi

2,8281 gold badge18 silver badges16 bronze badges

The immutable way to replace the element in the list using ES6 spread operators and .slice method.

const arr = ['fir', 'next', 'third'], item = 'next'

const nextArr = [
  ...arr.slice(0, arr.indexOf(item)), 
  'second',
  ...arr.slice(arr.indexOf(item) + 1)
]

Verify that works

console.log(arr)     // [ 'fir', 'next', 'third' ]
console.log(nextArr) // ['fir', 'second', 'third']

answered Jun 19, 2019 at 12:53

Purkhalo Alex's user avatar

1

Replacement can be done in one line:

var items = Array(523, 3452, 334, 31, 5346);

items[items.map((e, i) => [i, e]).filter(e => e[1] == 3452)[0][0]] = 1010

console.log(items);

Or create a function to reuse:

Array.prototype.replace = function(t, v) {
    if (this.indexOf(t)!= -1)
        this[this.map((e, i) => [i, e]).filter(e => e[1] == t)[0][0]] = v;
  };

//Check
var items = Array(523, 3452, 334, 31, 5346);
items.replace(3452, 1010);
console.log(items);

answered Jan 22, 2019 at 13:17

Artee's user avatar

ArteeArtee

8048 silver badges18 bronze badges

var items = Array(523,3452,334,31,5346);

If you know the value then use,

items[items.indexOf(334)] = 1010;

If you want to know that value is present or not, then use,

var point = items.indexOf(334);

if (point !== -1) {
    items[point] = 1010;
}

If you know the place (position) then directly use,

items[--position] = 1010;

If you want replace few elements, and you know only starting position only means,

items.splice(2, 1, 1010, 1220);

for more about .splice

answered Apr 26, 2015 at 3:10

KarSho's user avatar

KarShoKarSho

5,70113 gold badges44 silver badges78 bronze badges

The easiest way is to use some libraries like underscorejs and map method.

var items = Array(523,3452,334,31,...5346);

_.map(items, function(num) {
  return (num == 3452) ? 1010 : num; 
});
=> [523, 1010, 334, 31, ...5346]

answered Feb 11, 2014 at 21:35

mrded's user avatar

mrdedmrded

4,4242 gold badges32 silver badges36 bronze badges

0

If you want a simple sugar sintax oneliner you can just:

(elements = elements.filter(element => element.id !== updatedElement.id)).push(updatedElement);

Like:

let elements = [ { id: 1, name: 'element one' }, { id: 2, name: 'element two'} ];
const updatedElement = { id: 1, name: 'updated element one' };

If you don’t have id you could stringify the element like:

(elements = elements.filter(element => JSON.stringify(element) !== JSON.stringify(updatedElement))).push(updatedElement);

answered May 18, 2020 at 11:48

Marco Silva's user avatar

Marco SilvaMarco Silva

5545 silver badges14 bronze badges

var index = Array.indexOf(Array value);
        if (index > -1) {
          Array.splice(index, 1);
        }

from here you can delete a particular value from array and based on the same index
you can insert value in array .

 Array.splice(index, 0, Array value);

answered Aug 17, 2019 at 13:06

Gunjan Kumar's user avatar

Well if anyone is interresting on how to replace an object from its index in an array, here’s a solution.

Find the index of the object by its id:

const index = items.map(item => item.id).indexOf(objectId)

Replace the object using Object.assign() method:

Object.assign(items[index], newValue)

answered Feb 20, 2020 at 9:19

faye.babacar78's user avatar

1

 items[items.indexOf(3452)] = 1010

great for simple swaps. try the snippet below

const items = Array(523, 3452, 334, 31, 5346);
console.log(items)

items[items.indexOf(3452)] = 1010
console.log(items)

answered Oct 29, 2020 at 18:54

WhooNo's user avatar

WhooNoWhooNo

8212 gold badges11 silver badges26 bronze badges

Here is the basic answer made into a reusable function:

function arrayFindReplace(array, findValue, replaceValue){
    while(array.indexOf(findValue) !== -1){
        let index = array.indexOf(findValue);
        array[index] = replaceValue;
    }
}

answered Mar 13, 2018 at 21:43

JohnP2's user avatar

JohnP2JohnP2

1,83118 silver badges17 bronze badges

1

Here’s a one liner. It assumes the item will be in the array.

var items = [523, 3452, 334, 31, 5346]
var replace = (arr, oldVal, newVal) => (arr[arr.indexOf(oldVal)] = newVal, arr)
console.log(replace(items, 3452, 1010))

answered May 7, 2020 at 21:42

Alex Cory's user avatar

Alex CoryAlex Cory

9,7807 gold badges51 silver badges62 bronze badges

const items = Array(1, 2, 3, 4, 5);
console.log(items)

items[items.indexOf(2)] = 1010
console.log(items)

answered Apr 20, 2022 at 9:57

Raj Shah's user avatar

Raj ShahRaj Shah

5981 gold badge8 silver badges23 bronze badges

First, rewrite your array like this:

var items = [523,3452,334,31,...5346];

Next, access the element in the array through its index number. The formula to determine the index number is: n-1

To replace the first item (n=1) in the array, write:

items[0] = Enter Your New Number;

In your example, the number 3452 is in the second position (n=2). So the formula to determine the index number is 2-1 = 1. So write the following code to replace 3452 with 1010:

items[1] = 1010;

Jon Saw's user avatar

Jon Saw

7,1895 gold badges50 silver badges57 bronze badges

answered May 22, 2017 at 23:35

Anthony Levato's user avatar

I solved this problem using for loops and iterating through the original array and adding the positions of the matching arreas to another array and then looping through that array and changing it in the original array then return it, I used and arrow function but a regular function would work too.

var replace = (arr, replaceThis, WithThis) => {
    if (!Array.isArray(arr)) throw new RangeError("Error");
    var itemSpots = [];
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == replaceThis) itemSpots.push(i);
    }

    for (var i = 0; i < itemSpots.length; i++) {
        arr[itemSpots[i]] = WithThis;
    }

    return arr;
};

answered Oct 29, 2018 at 16:01

J. Svec's user avatar

presentPrompt(id,productqty) {
    let alert = this.forgotCtrl.create({
      title: 'Test',
      inputs: [
        {
          name: 'pickqty',
          placeholder: 'pick quantity'
        },
        {
          name: 'state',
          value: 'verified',
          disabled:true,
          placeholder: 'state',

        }
      ],
      buttons: [
        {
          text: 'Ok',
          role: 'cancel',
          handler: data => {

            console.log('dataaaaname',data.pickqty);
            console.log('dataaaapwd',data.state);


          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
                this.cottonLists[i].real_stock = data.pickqty;

            }
          }

          for (var i = 0; i < this.cottonLists.length; i++){

            if (this.cottonLists[i].id == id){
              this.cottonLists[i].state = 'verified';   

          }
        }
            //Log object to console again.
            console.log("After update: ", this.cottonLists)
            console.log('Ok clicked');
          }
        },

      ]
    });
    alert.present();
  }

As per your requirement you can change fields and array names.
thats all. Enjoy your coding.

answered Aug 27, 2019 at 6:11

mahendren's user avatar

mahendrenmahendren

1,07411 silver badges8 bronze badges

The easiest way is this.

var items = Array(523,3452,334,31, 5346);
var replaceWhat = 3452, replaceWith = 1010;
if ( ( i = items.indexOf(replaceWhat) ) >=0 ) items.splice(i, 1, replaceWith);

console.log(items);
>>> (5) [523, 1010, 334, 31, 5346]

answered Aug 31, 2019 at 14:09

Vladimir Prudnikov's user avatar

1

When your array have many old item to replace new item, you can use this way:

function replaceArray(array, oldItem, newItem) {
    for (let i = 0; i < array.length; i++) {
        const index = array.indexOf(oldItem);
        if (~index) {
            array[index] = newItem;
        }
    }
    return array
}

console.log(replaceArray([1, 2, 3, 2, 2, 8, 1, 9], 2, 5));
console.log(replaceArray([1, 2, 3, 2, 2, 8, 1, 9], 2, "Hi"));

answered Dec 12, 2021 at 8:24

Amir Kangarloo's user avatar

This will do the job

Array.prototype.replace = function(a, b) {
    return this.map(item => item == a ? b : item)
}

Usage:

let items = ['hi', 'hi', 'hello', 'hi', 'hello', 'hello', 'hi']
console.log(items.replace('hello', 'hi'))

Output:

['hi', 'hi', 'hi', 'hi', 'hi', 'hi', 'hi']

The nice thing is, that EVERY array will have .replace() property.

answered Apr 7, 2022 at 10:39

Krzysiek's user avatar

1

I am wondering if there is a more efficient way of swapping two elements in an Array, than doing something like this:

String temp = arr[1];
arr[1] = arr[2];
arr[2] = temp;

Well, this is obviously not bad or even wrong, but I need to swap very often so I am interested if there are any Libs or something that provide a more efficient way to do this?

greybeard's user avatar

greybeard

2,1207 gold badges27 silver badges61 bronze badges

asked Dec 7, 2012 at 15:38

Robin's user avatar

6

Nope. You could have a function to make it more concise each place you use it, but in the end, the work done would be the same (plus the overhead of the function call, until/unless HotSpot moved it inline — to help it with that, make the function static final).

answered Dec 7, 2012 at 15:40

T.J. Crowder's user avatar

T.J. CrowderT.J. Crowder

1.0m184 gold badges1874 silver badges1836 bronze badges

10

This should make it seamless:

public static final <T> void swap (T[] a, int i, int j) {
  T t = a[i];
  a[i] = a[j];
  a[j] = t;
}

public static final <T> void swap (List<T> l, int i, int j) {
  Collections.<T>swap(l, i, j);
}

private void test() {
  String [] a = {"Hello", "Goodbye"};
  swap(a, 0, 1);
  System.out.println("a:"+Arrays.toString(a));
  List<String> l = new ArrayList<String>(Arrays.asList(a));
  swap(l, 0, 1);
  System.out.println("l:"+l);
}

answered Dec 7, 2012 at 15:59

OldCurmudgeon's user avatar

OldCurmudgeonOldCurmudgeon

63.8k16 gold badges117 silver badges209 bronze badges

1

If you’re swapping numbers and want a concise way to write the code without creating a separate function or using a confusing XOR hack, I find this is much easier to understand and it’s also a one liner.

public static void swap(int[] arr, int i, int j) {
    arr[i] = (arr[i] + arr[j]) - (arr[j] = arr[i]);
}

What I’ve seen from some primitive benchmarks is that the performance difference is basically negligible as well.

This is one of the standard ways for swapping array elements without using a temporary variable, at least for integers.

answered Jan 28, 2017 at 15:13

kmecpp's user avatar

kmecppkmecpp

2,3011 gold badge22 silver badges38 bronze badges

2

If you want to swap string. it’s already the efficient way to do that.

However, if you want to swap integer, you can use XOR to swap two integers more efficiently like this:

int a = 1; int b = 2; a ^= b; b ^= a; a ^= b;

Mark's user avatar

Mark

1,7281 gold badge23 silver badges21 bronze badges

answered Dec 7, 2012 at 15:41

bhuang3's user avatar

bhuang3bhuang3

3,3632 gold badges16 silver badges16 bronze badges

9

Use Collections.swap and Arrays.asList:

Collections.swap(Arrays.asList(arr), i, j);

answered Sep 20, 2017 at 5:40

ZhekaKozlov's user avatar

ZhekaKozlovZhekaKozlov

35.1k20 gold badges118 silver badges149 bronze badges

2

inplace swapping (incase you already didn’t know) can save a bit of space by not creating a temp variable.

arr[i] = arr[i] + arr[j];
arr[j] = arr[i] - arr[j];
arr[i] = arr[i] - arr[j];

answered Jan 21, 2021 at 0:44

Neel Alex's user avatar

Neel AlexNeel Alex

5554 silver badges10 bronze badges

Incredibly late to the party (my apologies) but a more generic solution than those provided here can be implemented (will work with primitives and non-primitives alike):

public static void swap(final Object array, final int i, final int j) {
    final Object atI = Array.get(array, i);
    Array.set(array, i, Array.get(array, j));
    Array.set(array, j, atI);
}

You lose compile-time safety, but it should do the trick.

Note I: You’ll get a NullPointerException if the given array is null, an IllegalArgumentException if the given array is not an array, and an ArrayIndexOutOfBoundsException if either of the indices aren’t valid for the given array.

Note II: Having separate methods for this for every array type (Object[] and all primitive types) would be more performant (using the other approaches given here) since this requires some boxing/unboxing. But it’d also be a whole lot more code to write/maintain.

answered Aug 2, 2017 at 1:09

BeUndead's user avatar

BeUndeadBeUndead

3,3832 gold badges17 silver badges21 bronze badges

Try this:

    int lowIndex = 0;
    int highIndex = elements.length-1;

    while(lowIndex < highIndex) {
        T lowVal = elements[lowIndex];
        T highVal = elements[highIndex];
        elements[lowIndex] = highVal;
        elements[highIndex] = lowVal;

        lowIndex += 1;
        highIndex -=1;
    }

answered Aug 11, 2017 at 15:29

J.user94's user avatar

1

public static final void swap (int[] a, int i, int j) {
    a[i] = a[i] + a[j];
    a[j] = a[i] - a[j];
    a[i] = a[i] - a[j];
}

answered Sep 22, 2021 at 10:03

Anil's user avatar

AnilAnil

1231 silver badge7 bronze badges

1

first of all you shouldn’t write for (int k = 0; k **<** data.length **- 1**; k++)because the < is until the k is smaller the length -1 and then the loop will run until the last position in the array and won’t get the last place in the array;
so you can fix it by two ways:
1: for (int k = 0; k <= data.length - 1; k++)
2: for (int k = 0; k < data.length; k++) and then it will work fine!!!
and to swap you can use: to keep one of the int’s in another place and then to replace

int x = data[k]
data[k] = data[data.length - 1]
data[data.length - 1] = x;

because you don’t want to lose one of the int’s!!

answered Apr 24, 2019 at 19:14

viper-zero's user avatar

viper-zeroviper-zero

411 gold badge1 silver badge9 bronze badges

1

Solution for object and primitive types:

public static final <T> void swap(final T[] arr, final int i, final int j) {
    T tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final boolean[] arr, final int i, final int j) {
    boolean tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final byte[] arr, final int i, final int j) {
    byte tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final short[] arr, final int i, final int j) {
    short tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final int[] arr, final int i, final int j) {
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final long[] arr, final int i, final int j) {
    long tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final char[] arr, final int i, final int j) {
    char tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final float[] arr, final int i, final int j) {
    float tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final double[] arr, final int i, final int j) {
    double tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

answered Jun 15, 2019 at 21:49

Error404's user avatar

Error404Error404

71810 silver badges28 bronze badges

This is just «hack» style method:

int d[][] = new int[n][n];

static int swap(int a, int b) {
  return a;
}
...

in main class --> 

d[i][j + 1] = swap(d[i][j], d[i][j] = d[i][j + 1])

answered Aug 11, 2020 at 1:34

ellerymoon's user avatar

public class SwapElements {

public static void main(String[] args) {

    int[] arr1 = new int[5];
    int[] arr2 = {10,20,30,40};

    System.out.println("arr1 Before Swapping " + Arrays.toString(arr1));
    System.out.println("arr2 Before Swapping " + Arrays.toString(arr2));

    int temp[];
    arr1[3] = 5;
    arr1[0] = 2;
    arr1[1] = 3;
    arr1[2] = 6;
    arr1[4] = 10;

    temp = arr1;
    arr1 = arr2;
    arr2 = temp;
    System.out.println("arr1 after Swapping " + Arrays.toString(arr1));
    System.out.println("arr2 after Swapping " + Arrays.toString(arr2));
}

}

answered Feb 12, 2020 at 3:00

Anu Sathiya's user avatar

1

I am wondering if there is a more efficient way of swapping two elements in an Array, than doing something like this:

String temp = arr[1];
arr[1] = arr[2];
arr[2] = temp;

Well, this is obviously not bad or even wrong, but I need to swap very often so I am interested if there are any Libs or something that provide a more efficient way to do this?

greybeard's user avatar

greybeard

2,1207 gold badges27 silver badges61 bronze badges

asked Dec 7, 2012 at 15:38

Robin's user avatar

6

Nope. You could have a function to make it more concise each place you use it, but in the end, the work done would be the same (plus the overhead of the function call, until/unless HotSpot moved it inline — to help it with that, make the function static final).

answered Dec 7, 2012 at 15:40

T.J. Crowder's user avatar

T.J. CrowderT.J. Crowder

1.0m184 gold badges1874 silver badges1836 bronze badges

10

This should make it seamless:

public static final <T> void swap (T[] a, int i, int j) {
  T t = a[i];
  a[i] = a[j];
  a[j] = t;
}

public static final <T> void swap (List<T> l, int i, int j) {
  Collections.<T>swap(l, i, j);
}

private void test() {
  String [] a = {"Hello", "Goodbye"};
  swap(a, 0, 1);
  System.out.println("a:"+Arrays.toString(a));
  List<String> l = new ArrayList<String>(Arrays.asList(a));
  swap(l, 0, 1);
  System.out.println("l:"+l);
}

answered Dec 7, 2012 at 15:59

OldCurmudgeon's user avatar

OldCurmudgeonOldCurmudgeon

63.8k16 gold badges117 silver badges209 bronze badges

1

If you’re swapping numbers and want a concise way to write the code without creating a separate function or using a confusing XOR hack, I find this is much easier to understand and it’s also a one liner.

public static void swap(int[] arr, int i, int j) {
    arr[i] = (arr[i] + arr[j]) - (arr[j] = arr[i]);
}

What I’ve seen from some primitive benchmarks is that the performance difference is basically negligible as well.

This is one of the standard ways for swapping array elements without using a temporary variable, at least for integers.

answered Jan 28, 2017 at 15:13

kmecpp's user avatar

kmecppkmecpp

2,3011 gold badge22 silver badges38 bronze badges

2

If you want to swap string. it’s already the efficient way to do that.

However, if you want to swap integer, you can use XOR to swap two integers more efficiently like this:

int a = 1; int b = 2; a ^= b; b ^= a; a ^= b;

Mark's user avatar

Mark

1,7281 gold badge23 silver badges21 bronze badges

answered Dec 7, 2012 at 15:41

bhuang3's user avatar

bhuang3bhuang3

3,3632 gold badges16 silver badges16 bronze badges

9

Use Collections.swap and Arrays.asList:

Collections.swap(Arrays.asList(arr), i, j);

answered Sep 20, 2017 at 5:40

ZhekaKozlov's user avatar

ZhekaKozlovZhekaKozlov

35.1k20 gold badges118 silver badges149 bronze badges

2

inplace swapping (incase you already didn’t know) can save a bit of space by not creating a temp variable.

arr[i] = arr[i] + arr[j];
arr[j] = arr[i] - arr[j];
arr[i] = arr[i] - arr[j];

answered Jan 21, 2021 at 0:44

Neel Alex's user avatar

Neel AlexNeel Alex

5554 silver badges10 bronze badges

Incredibly late to the party (my apologies) but a more generic solution than those provided here can be implemented (will work with primitives and non-primitives alike):

public static void swap(final Object array, final int i, final int j) {
    final Object atI = Array.get(array, i);
    Array.set(array, i, Array.get(array, j));
    Array.set(array, j, atI);
}

You lose compile-time safety, but it should do the trick.

Note I: You’ll get a NullPointerException if the given array is null, an IllegalArgumentException if the given array is not an array, and an ArrayIndexOutOfBoundsException if either of the indices aren’t valid for the given array.

Note II: Having separate methods for this for every array type (Object[] and all primitive types) would be more performant (using the other approaches given here) since this requires some boxing/unboxing. But it’d also be a whole lot more code to write/maintain.

answered Aug 2, 2017 at 1:09

BeUndead's user avatar

BeUndeadBeUndead

3,3832 gold badges17 silver badges21 bronze badges

Try this:

    int lowIndex = 0;
    int highIndex = elements.length-1;

    while(lowIndex < highIndex) {
        T lowVal = elements[lowIndex];
        T highVal = elements[highIndex];
        elements[lowIndex] = highVal;
        elements[highIndex] = lowVal;

        lowIndex += 1;
        highIndex -=1;
    }

answered Aug 11, 2017 at 15:29

J.user94's user avatar

1

public static final void swap (int[] a, int i, int j) {
    a[i] = a[i] + a[j];
    a[j] = a[i] - a[j];
    a[i] = a[i] - a[j];
}

answered Sep 22, 2021 at 10:03

Anil's user avatar

AnilAnil

1231 silver badge7 bronze badges

1

first of all you shouldn’t write for (int k = 0; k **<** data.length **- 1**; k++)because the < is until the k is smaller the length -1 and then the loop will run until the last position in the array and won’t get the last place in the array;
so you can fix it by two ways:
1: for (int k = 0; k <= data.length - 1; k++)
2: for (int k = 0; k < data.length; k++) and then it will work fine!!!
and to swap you can use: to keep one of the int’s in another place and then to replace

int x = data[k]
data[k] = data[data.length - 1]
data[data.length - 1] = x;

because you don’t want to lose one of the int’s!!

answered Apr 24, 2019 at 19:14

viper-zero's user avatar

viper-zeroviper-zero

411 gold badge1 silver badge9 bronze badges

1

Solution for object and primitive types:

public static final <T> void swap(final T[] arr, final int i, final int j) {
    T tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final boolean[] arr, final int i, final int j) {
    boolean tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final byte[] arr, final int i, final int j) {
    byte tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final short[] arr, final int i, final int j) {
    short tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final int[] arr, final int i, final int j) {
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final long[] arr, final int i, final int j) {
    long tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final char[] arr, final int i, final int j) {
    char tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final float[] arr, final int i, final int j) {
    float tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final double[] arr, final int i, final int j) {
    double tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

answered Jun 15, 2019 at 21:49

Error404's user avatar

Error404Error404

71810 silver badges28 bronze badges

This is just «hack» style method:

int d[][] = new int[n][n];

static int swap(int a, int b) {
  return a;
}
...

in main class --> 

d[i][j + 1] = swap(d[i][j], d[i][j] = d[i][j + 1])

answered Aug 11, 2020 at 1:34

ellerymoon's user avatar

public class SwapElements {

public static void main(String[] args) {

    int[] arr1 = new int[5];
    int[] arr2 = {10,20,30,40};

    System.out.println("arr1 Before Swapping " + Arrays.toString(arr1));
    System.out.println("arr2 Before Swapping " + Arrays.toString(arr2));

    int temp[];
    arr1[3] = 5;
    arr1[0] = 2;
    arr1[1] = 3;
    arr1[2] = 6;
    arr1[4] = 10;

    temp = arr1;
    arr1 = arr2;
    arr2 = temp;
    System.out.println("arr1 after Swapping " + Arrays.toString(arr1));
    System.out.println("arr2 after Swapping " + Arrays.toString(arr2));
}

}

answered Feb 12, 2020 at 3:00

Anu Sathiya's user avatar

1

array_replace

(PHP 5 >= 5.3.0, PHP 7)

array_replaceЗамена элементов массива элементами других переданных массивов

Описание

array array_replace
( array $array1
, array $array2
[, array $...
] )

array_replace() замещает значения массива
array1 значениями с такими же ключами из
других переданных массивов. Если ключ из первого массива присутствует
во втором массиве, его значение заменяется на значение из второго массива.
Если ключ есть во втором массиве, но отсутствует в первом — он будет создан
в первом массиве. Если ключ присутствует только в первом массиве, то
сохранится как есть. Если для замены передано несколько массивов, они
будут обработаны в порядке передачи и более поздние массивы будут
перезаписывать значения из предыдущих.

array_replace() не рекурсивная: значения первого массива
будут заменены вне зависимости от типа значений второго массива, даже если
это будут вложенные массивы.

Список параметров

array1

Массив, элементы которого требуется заменить.

array2

Массив, элементами которого будут заменяться элементы первого массива.

...

Еще массивы, из которых будут браться элементы для замены.
Значения следующего массива затирают значения предыдущего.

Возвращаемые значения

Возвращает массив (array) или NULL в случае ошибки.

Примеры

Пример #1 Пример использования array_replace()


<?php
$base 
= array("orange""banana""apple""raspberry");
$replacements = array(=> "pineapple"=> "cherry");
$replacements2 = array(=> "grape");$basket array_replace($base$replacements$replacements2);
print_r($basket);
?>

Результат выполнения данного примера:

Array
(
    [0] => grape
    [1] => banana
    [2] => apple
    [3] => raspberry
    [4] => cherry
)

Смотрите также

  • array_replace_recursive() — Рекурсивно заменяет элементы первого массива элементами переданных массивов
  • array_merge() — Сливает один или большее количество массивов

Вернуться к: Функции для работы с массивами

Как можно заменить значение в массиве по ключу с примерами

Как заменить значение массива по ключу, вообще в любом массиве. Приведем несколько вариантов смены значений по ключу в массиве! В разных видах массивов

Все способы замены значений по ключу в разных видах массивов

  1. Заменить значение по ключу в простом массиве
  2. Замена значения по ключу в любом массиве
  3. Заменить значение по ключу в в цикле
  4. Замена значения по ключу в ассоциативном массиве
  1. Заменить значение по ключу в простом массиве

    Для того, чтобы продемонстрировать замену значения по ключу в простом массиве нам потребуется:

    Простой массив, в котором мы и будем менять значение ячейки массива по ключу

    $example_simple_array = array(‘кошка’,’собака’,’корова’,’курица’,’слон’,’тигр’ );

    Выведем данный массив прямо здесь через print_r

    Array
    (
    [0] => кошка
    [1] => собака
    [2] => корова
    [3] => курица
    [4] => слон
    [5] => тигр
    )

    Предположим, что нам требуется заменить значение ячейки массива в ключе номер 1, нам просто требуется этой ячейке присвоить новое значение:

    $example_simple_array [1] = ‘таракан’;

    После этой строки опять выводим наш массив и посмотрим, произошла ли замена значения по ключу в ячейке массива:

    Array
    (
    [0] => кошка
    [1] => таракан
    [2] => корова
    [3] => курица
    [4] => слон
    [5] => тигр
    )

    Как видим, наше значение в ячейки массива заменилось по ключу, как нам и требовалось

  2. Замена значения по ключу в любом массиве

    Как вы наверное знаете, что массивы бывают разными, как заменить значение ячейки массива в любом массиве!?

    Я вам дам простой совет, как это сделать!

    Самая главная проблема в такого рода заменах в том. что трудно бывает обратиться к ячейке массива, как мы видели выше, обратиться к ячейке простого массива достаточно просто:

    $example_simple_array [1] = ‘таракан’;

    В ассоциативных массивах и многомерных со сложной структурой, порой довольно трудно обратиться к ячейке, поэтому, прежде чем делать какие-то действия замены, просто выведите значение данной ячейки на экран. Для примера возьмем уже использованный нами многомерный массив

    $переменная = array (
    «Иванов» => array («рост» => 174, «вес» => 68),
    «Петров» => array («рост» => 181, «вес» => 90),
    «Сидоров» => array («рост» => 166, «вес» => 73));

    Далее создаем путь до требуемой ячейки, и проверим с помощью вывода echo

    echo $переменная[Иванов][вес];

    Результат:

    68

    И раз у нас все прошло удачно, то теперь мы спокойно по данному ключу можем заменить значение в любом массиве

    $переменная[Иванов][вес] =200;

    И выведем результат замены значения по ключу в массиве:

    Array
    (
    [Иванов] => Array
    (
    [рост] => 174
    [вес] => 200
    )

    [Петров] => Array
    (
    [рост] => 181
    [вес] => 90
    )

    [Сидоров] => Array
    (
    [рост] => 166
    [вес] => 73
    )

    )

    Как видим значение ячейки массива $переменная[Иванов][вес] изменилось на 200… тебе дружочек похудеть бы не мешало! wall
    смайлы

  3. Заменить значение по ключу в в цикле

    Вообще на тему замены значения по ключу в массиве, довольно сложно что-то еще написать…

    В жизни всякое случается и встречаются ситуации, что нужно в цикле по ключу заменить какое-то значение в массиве.

    В зависимости от цикла, создаем условие, путь это будет цикл for:

    for ($i=0; $i < count($array) ; $i++) {
    if([$i] ==»

    Искомый номер ключа…

    «) { $array[$i] = «

    Новое значение

    «;}

    }

Можете не благодарить, лучше помогите!

COMMENTS+

 
BBcode



Содержание

  • 1. Метод add(). Добавить элемент в конец массива
  • 2. Метод addAll(). Добавить коллекцию к массиву
  • 3. Метод clear(). Очистить массив
  • 4. Метод remove(). Удалить элемент в указанной позиции
  • 5. Метод removeAll(). Удалить группу элементов из коллекции
  • 6. Метод removeIf(). Изменить коллекцию на основе предиката
  • 7. Метод replaceAll(). Произвести вычисления над каждым элементом массива
  • 8. Метод set(). Установить новое значение в элементе
  • 9. Метод sort(). Отсортировать элементы массива
  • Связанные темы

Поиск на других ресурсах:

1. Метод add(). Добавить элемент в конец массива

Метод add() добавляет элемент в массив. Метод имеет две перегруженные реализации

add(E obj)
add(int index, E obj)

здесь

  • E – тип элементов массива;
  • obj – объект (элемент), добавляемый к массиву;
  • index – позиция, в которую нужно вставить элемент obj в массив.

Пример. В примере формируется массив квадратов чисел от 1 до 10. Для добавления числа в конец массива используется метод add().

import java.util.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Метод addAll() - добавить элемент в конец массива
    // 1. Создать массив из чисел типа Integer
    ArrayList<Integer> AI = new ArrayList();

    // 2. Добавить в массив квадраты чисел от 1 до 10
    for (int i=1; i<=10; i++)
      AI.add(i*i);

    // 3. Вывести массив
    System.out.println(AI);

    // 4. Добавить число 555 на начало массива в позицию 0
    AI.add(0, 555);
    System.out.println(AI);
  }
}

Результат выполнения программы

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
[555, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 

2. Метод addAll(). Добавить коллекцию к массиву

Метод addAll() предназначен для добавления уже существующей коллекции в массив. Коллекцией могут быть коллекция, очередь, другой массив и т.д. Метод имеет две перегруженные реализации

addAll(Collection<? extends E>)
addAll(int index, Collection<? extends E>)

здесь

  • E – тип элементов массива (коллекции);
  • index – позиция, с которой происходит вставка.

Пример. Демонстрируется использование метода addAll() для массива целых чисел.

import java.util.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Метод addAll() - добавить коллекцию к массиву
    // 1. Создать массив из 5 чисел типа Float
    ArrayList<Float> AI = new ArrayList();
    AI.add(1.0f);
    AI.add(2.0f);
    AI.add(3.0f);
    AI.add(4.0f);
    AI.add(5.0f);
    System.out.println("AI = " + AI);

    // 2. Создать другой массив из 3 чисел типа Float
    ArrayList<Float> AI2 = new ArrayList();
    for (int i=1; i<=3; i++)
      AI2.add(i*15f);
    System.out.println("AI2 = " + AI2);

    // 3. Добавить массив AI2 в конец массива AI
    AI.addAll(AI2);
    System.out.println("AI + AI2 = " + AI);

    // 4. Записать массив AI2 в массив AI начиная с позиции 2
    AI.addAll(2, AI2);
    System.out.println("AI[2] + AI2 = " + AI);
  }
}

Результат выполнения программы

AI = [1.0, 2.0, 3.0, 4.0, 5.0]
AI2 = [15.0, 30.0, 45.0]
AI + AI2 = [1.0, 2.0, 3.0, 4.0, 5.0, 15.0, 30.0, 45.0]
AI[2] + AI2 = [1.0, 2.0, 15.0, 30.0, 45.0, 3.0, 4.0, 5.0, 15.0, 30.0, 45.0]

 

3. Метод clear(). Очистить массив

Метод clear() предназначен для очищения массива. Согласно документации общая форма объявления метода следующая

public void clear();

Пример. В примере создается коллекция из символов-разделителей.

import java.util.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Метод clear() - очистить коллекцию
    // 1. Создать коллекцию из разделительных символов в предложении
    ArrayList<Character> AL = new ArrayList();
    AL.add(';');
    AL.add(':');
    AL.add(',');
    AL.add('.');
    AL.add('!');
    AL.add('?');
    AL.add(' ');

    // 2. Вывести коллекцию
    System.out.println("AL => " + AL);

    // 3. Очистить коллекцию
    AL.clear();

    // 4. Вывести коллекцию после очистки
    System.out.println("AL.clear() => " + AL);
  }
}

Результат выполнения программы

AL => [;, :, ,, ., !, ?,  ]
AL.clear() => []

 

4. Метод remove(). Удалить элемент в указанной позиции

С помощью метода remove() можно удалить элемент в заданной позиции. Согласно документации, объявление метода следующее

public E remove(int index);

здесь

  • E – тип элементов массива (коллекции);
  • index – номер позиции, которую нужно удалить. Позиция нумеруется с 0.

Метод возвращает значение удаляемого элемента из массива (коллекции).

Если значение index указано за пределами допустимого диапазона

(index < 0 || index >= size())

то будет сгенерировано исключение IndexOutOfBoundsException.

Пример.

import java.util.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Метод remove() - удалить отдельный элемент из массива
    // 1. Создать коллекцию вещественных чисел
    ArrayList<Float> AL = new ArrayList<Float>();
    AL.add(2.8f);
    AL.add(3.5f);
    AL.add(7.2f);
    AL.add(9.4f);
    AL.add(5.2f);

    // 2. Вывести коллекцию
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();

    // 3. Удалить элемент в позиции 2, который имеет значение 7.2
    AL.remove(2);

    // 4. Вывести измененную коллекцию
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
  }
}

Результат выполнения программы

AL => 2.8  3.5  7.2  9.4  5.2
AL => 2.8  3.5  9.4  5.2

 

5. Метод removeAll(). Удалить группу элементов из коллекции

С помощью метода removeAll() можно удалить несколько элементов, представленных в виде коллекции. Согласно документации объявление метода следующее:

public boolean removeAll(Collection<?> c);

здесь

  • c – коллекция (массив) элементов, которые нужно удалить из текущей коллекции.

Метод возвращает true, если текущий массив изменился в результате вызова.

Пример.

В примере формируются две целочисленные коллекции:

  • AL – исходная коллекция чисел;
  • AL2 – коллекция чисел, которые необходимо удалить из коллекции AL.

С помощью метода removeAll() происходит удаление из коллекции AL всех частей, входящих в коллекцию AL2.

import java.util.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Метод removeAll() - удалить группу элементов из массива
    // 1. Создать коллекцию целых чисел
    ArrayList<Integer> AL = new ArrayList<Integer>();
    AL.add(2);
    AL.add(3);
    AL.add(2);
    AL.add(4);
    AL.add(7);
    AL.add(3);
    AL.add(4);
    AL.add(5);
    AL.add(6);
    AL.add(1);

    // 2. Вывести исходную коллекцию
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();

    // 3. Создать коллекцию чисел, которые нужно удалить
    ArrayList<Integer> AL2 = new ArrayList<Integer>();

    // удалить все числа 2, 4, 7
    AL2.add(2);
    AL2.add(4);
    AL2.add(7);

    // 4. Вызвать метод removeAll()
    AL.removeAll(AL2);

    // 4. Вывести измененную коллекцию
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
  }
}

Результат выполнения программы

AL => 2  3  2  4  7  3  4  5  6  1
AL => 3  3  5  6  1

 

6. Метод removeIf(). Изменить коллекцию на основе предиката

С помощью метода removeIf() можно удалить элементы из коллекции согласно условию. В результате формируется новая коллекция (массив). Общая форма объявления метода следующая

public boolean removeIf(Predicate<? super E> filter);

здесь

  • filter – ссылка (предикат), определяющее условие фильтрования. Условие задается лямбда-выражением.

Метод возвращает true, если хотя бы один элемент был удалён.

Пример.

В примере демонстрируется выполнение метода removeIf(). Демонстрируются следующие операции:

  • создается коллекция целых чисел;
  • формируется предикат, в котором определяются числа, которые больше 4;
  • вызывается метод removeIf(), с помощью которого формируется новый массив чисел согласно предикату.
import java.util.*;
import java.util.function.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Метод removeIf() - изменить массив по заданному условию
    // 1. Создать коллекцию целых чисел
    ArrayList<Integer> AL = new ArrayList<Integer>();
    AL.add(2);
    AL.add(3);
    AL.add(2);
    AL.add(4);
    AL.add(7);
    AL.add(3);
    AL.add(4);
    AL.add(5);
    AL.add(6);
    AL.add(1);

    // 2. Вывести исходную коллекцию
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();

    // 3. Объявить ссылку на интерфейс Predicate<Integer>
    Predicate<Integer> ref;

    // 4. Сформировать условие для ссылки ref на основе лямбда-выражения:
    //    взять все числа, которые больше 4
    ref = (value) -> value > 4;

    // 5. Вызвать метод removeIf() и передать ему ссылку ref условием
    AL.removeIf(ref);    // удалить все числа, которые больше 4

    // 6. Вывести измененный массив AL
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();
  }
}

Результат выполнения программы

AL => 2  3  2  4  7  3  4  5  6  1
AL => 2  3  2  4  3  4  1

 

7. Метод replaceAll(). Произвести вычисления над каждым элементом массива

С помощью метода replaceAll() можно применить некоторую операцию к каждому элементу массива. Такой операцией может быть, например произведение каждого элемента на 2. Согласно документации, общая форма объявления метода следующая:

public void replaceAll(UnaryOperator<E> operator);

здесь

  • operator – лямбда-выражение, определяющее операцию над каждым элементом последовательности. Лямбда-выражение формируется с помощью функционального интерфейса UnaryOperator<T>.

Пример. В примере создается массив целых чисел. Затем каждый элемент массива умножается на 3 с помощью метода replaceAll(). Для выполнения вычисления формируется ссылка на подходящее лямбда-выражение.

import java.util.*;
import java.util.function.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Метод replaceAll() - изменить значение элементов исходного массива
    // 1. Создать коллекцию целых чисел
    ArrayList<Integer> AL = new ArrayList<Integer>();
    AL.add(2);
    AL.add(3);
    AL.add(2);
    AL.add(4);
    AL.add(7);
    AL.add(3);

    // 2. Вывести коллекцию с помощью итератора
    Iterator<Integer> it = AL.iterator();
    System.out.print("AL => ");
    while (it.hasNext())
      System.out.print(it.next()+"  ");
    System.out.println();

    // 3. Сформировать лямбда-выражение, которое умножает элемент на 3
    UnaryOperator<Integer> op = (num) -> num*3;

    // 4. Вызвать метод replaceAll() и применить к нему оператор op
    AL.replaceAll(op);

    // 5. Вывести измененную коллекцию (массив) целых чисел
    it = AL.iterator();
    System.out.print("AL => ");

    while (it.hasNext()) {
      System.out.print(it.next() + "  ");
    }
  }
}

Результат выполнения программы

AL => 2  3  2  4  7  3
AL => 6  9  6  12  21  9

 

8. Метод set(). Установить новое значение в элементе

Метод set() устанавливает новое значение в заданной позиции массива. Другими словами, старое значение массива в заданной позиции заменяется новым. Объявление метода имеет вид

public E set(int index, E element);

здесь

  • index – позиция вставки (нумеруется с 0);
  • element – новое значение, которое необходимо установить в позиции index.

Метод возвращает предыдущее значение, установленное в заданной позиции.

Если значение index выходит за пределы допустимого диапазона, т.е.

(index < 0 || index >= size())

то будет сгенерировано исключение IndexOutOfBoundsException.

Приклад.

import java.util.*;
import java.util.function.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Метод set() - установить значение в отдельном элементе массива
    // 1. Создать коллекцию строк
    ArrayList<String> AL = new ArrayList<String>();
    AL.add("a");
    AL.add("b");
    AL.add("c");

    // 2. Вывести исходный массив с помощью итератора
    Iterator<String> it = AL.iterator();
    System.out.print("AL => ");
    while (it.hasNext())
      System.out.print(it.next()+"  ");
    System.out.println();

    // 3. Установить новое значение в элементе с индексом 1
    String oldValue;
    oldValue = AL.set(1, "bbb");

    // 4. Вывести предыдущую строку
    System.out.println("oldValue = " + oldValue);

    // 5. Вывести измененный массив
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();
  }
}

Результат выполнения программы

AL => a  b  c
oldValue = b
AL => a  bbb  c

 

9. Метод sort(). Отсортировать элементы массива

С помощью метода sort() можно сортировать элементы массива. Общая форма объявления метода следующая

public void sort(Comparator<? super E> c);

здесь

  • c – компаратор (условие), реализующий принцип сравнения каких-либо двух элементов массива. Компаратор используется в случае разработки собственного класса, объекты которого могут быть отсортированы по некоторому критерию. В этом случае класс должен реализовать интерфейс Comparator. В этом интерфейсе определен метод compare(), сравнивающий два элемента. Конкретно этот способ нужно переопределить и воплотить в этом классе и задать свой механизм сравнения.

Для стандартных типов-оболочек (Integer, Double, String и т.д.) реализован внутренний компаратор, сортирующий элементы в естественном порядке (от меньшего к большему или по алфавиту).

Для использования стандартного способа сортировки следует вызвать метод sort() с аргументом null

AL.sort(null);

здесь AL – массив сортируемых элементов.

Пример.

import java.util.*;
import java.util.function.*;

public class TrainCollections {

  public static void main(String[] args) {
    // Метод sort() - сортировка в естественном порядке
    // 1. Создать массив строк
    ArrayList<String> AL = new ArrayList<String>();
    AL.add("jklm");
    AL.add("abcd");
    AL.add("elsd");
    AL.add("lkls");
    AL.add("azsd");

    // 2. Вывести исходный массив
    Iterator<String> it = AL.iterator();
    System.out.print("AL => ");
    while (it.hasNext())
      System.out.print(it.next()+"  ");
    System.out.println();

    // 3. Отсортировать элементы массива, метод sort()
    AL.sort(null);

    // 4. Вывести отсортированный массив
    System.out.print("AL => ");
    for (int i=0; i<AL.size(); i++)
      System.out.print(AL.get(i) + "  ");
    System.out.println();
  }
}

Результат выполнения программы

AL => jklm  abcd  elsd  lkls  azsd
AL => abcd  azsd  elsd  jklm  lkls

 


Связанные темы

  • Класс ArrayList. Динамический массив. Общие сведения. Создание массива
  • Методы, определяющие информацию об элементах массива. Методы get(), contains(), containsAll(), indexOf(), lastIndexOf(), iterator(), listIterator()
  • Методы определяющие общие характеристики массива. Методы ensureCapacity(), isEmpty(), size(), trimToSize() 
  • Методы преобразующие массив в целом. Методы clone(), sublist(), toArray(), retainAll()

 


Понравилась статья? Поделить с друзьями:

Читайте также:

  • Как изменить значение массива php
  • Как изменить значение кнопок на мыши
  • Как изменить значение кнопок на клавиатуре ноутбука
  • Как изменить значение кнопок на геймпаде
  • Как изменить значение кнопки выключения компьютера windows 10

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии